首页 > 代码库 > 【Lintcode】046.Majority Number

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

Have you met this question in a real interview? 
Yes
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;
    }
};

 

【Lintcode】046.Majority Number