首页 > 其他 > 详细

【Lintcode】046.Majority Number

时间:2017-05-26 20:27:35      阅读:261      评论:0      收藏:0      [点我收藏+]

题目:

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;
    }
};

 

【Lintcode】046.Majority Number

原文:http://www.cnblogs.com/Atanisi/p/6910262.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!