169. 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.

本题最简便的方法是摩尔投票法。由于序列中一个有某个元素的出现次数超过序列长度的一半。不妨设置一个计数值count和一个候选值majority,令count的初始值为0,majority的初始值为nums[0],然后遍历整个序列。当majority == nums[i]时,计数值count递增。当majority != nums[i]时,递减计数器count值。当count == 0时,重新设定majority = nums[i]。这样当整个序列全部遍历完成后,majority的值必定就是符合题设条件的元素值。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int res = 0, cnt = 0;
        for (int num : nums) {
            if (cnt == 0) {res = num; ++cnt;}
            else (num == res) ? ++cnt : --cnt;
        }
        return res;
    }
};

 

posted @ 2017-06-08 15:53  NaiveCoder  阅读(93)  评论(0)    收藏  举报