169. Majority Element

来源:互联网 发布:第三类顶级域名 编辑:程序博客网 时间:2024/06/11 04:05

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.
题目含义:
给定大小为n的数组,找到多数元素。多数元素是出现次数以上 的元素⌊ n/2 ⌋
您可以假定该数组不为空,并且多数元素始终存在于数组中。
思想:可以使用莫尔德投票算法
算法描述
算法在局部变量中定义一个序列元素(m)和一个计数器(i),初始化的情况下计数器为0. 算法依次扫描序列中的元素,当处理元素x的时候,如果计数器为0,那么将x赋值给m,如果计数器不为0,那么将序列元素m和x比较,如果相等,那么计数器加1,如果不等,那么计数器减1。处理之后,最后存储的序列元素(m),就是这个序列中最多的元素。
C++ AC代码:时间o(n) 空间o(1)
class Solution {public:    int majorityElement(vector<int>& nums) {        int len = nums.size();        int variable;        int times=0;        for(int i=0;i<len;i++){             if(times==0){                variable=nums[i];            }            if(variable==nums[i])                times++;            else                times--;                    }        return variable;    }};