【Lintcode】046.Majority Number

题目:

Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

 Notice

You may assume that the array is non-empty and the majority number always exist in the array.

Example

Given [1, 1, 1, 1, 2, 2, 2], return 1

题解:

  摩尔投票法

Solution 1 ()

class Solution {
public:
    int majorityNumber(vector<int> nums) {
        int cnt = 0;
        int res = nums[0];
        for(auto n : nums) {
            if (n == res) {
                cnt++;
                continue;
            } else {
                if(--cnt <= 0) {
                    cnt = 1;
                    res = n;
                }
            }
        }
        return res;
    }
};

 

posted @ 2017-05-26 20:05  Vincent丶丶  阅读(259)  评论(0)    收藏  举报