169. Majority Element

来源:互联网 发布:南极人枕芯怎么样 知乎 编辑:程序博客网 时间:2024/06/04 19:30

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.

摩尔投票法:http://mabusyao.iteye.com/blog/2223195
这种投票法先将第一个数字假设为众数,然后把计数器设为1,比较下一个数和此数是否相等,若相等则计数器加一,反之减一。然后看此时计数器的值,若为零,则将当前值设为候选众数。以此类推直到遍历完整个数组,当前候选众数即为该数组的众数。代码如下

class Solution {public:    int majorityElement(vector<int>& nums) {        int nowNum = nums[0];        int count = 1;        for(int i = 1; i < nums.size() ; i ++){            if(count == 0){                nowNum = nums[i];                count = 1;            }else{                if(nums[i] == nowNum){                    count ++;                }else{                    count --;                }            }        }        return nowNum;    }};
0 0
原创粉丝点击