Lintcode046.Majority Number

Posted Vincent丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lintcode046.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;
    }
};

 

以上是关于Lintcode046.Majority Number的主要内容,如果未能解决你的问题,请参考以下文章

python切片

lintcode:单词切分

LintCode Subtree

使用awk对某一列进行求和计算

绝对值查找器的娱乐没有按预期工作

LintCode Longest Common Subsequence