Majority Element

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.

本题的解法是假设数组中一定存在这样的绝对众数。如果没有这样的假设,这种做法只能算是求出候选值,需要再次遍历,计算该数在数组中出现的次数,得出是不是绝对众数的结论。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int count = 0;
        int m = nums[0];
        for (size_t i = 0; i < nums.size(); i++) {
            if (count == 0) {
                m = nums[i];
                count = 1;
            } else if (nums[i] != m) {
                count--;
            } else {
                count++;
            }
        }
        return m;
    }
};

 

posted @ 2016-10-09 10:40  wxquare  阅读(166)  评论(0编辑  收藏  举报