首页 > 其他 > 详细

[LintCode] Majority Number 求众数

时间:2016-11-16 13:51:16      阅读:316      评论: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

Challenge

O(n) time and O(1) extra space

 

LeetCode上的原题,请参见我之前的博客Majority Element

 

解法一:

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: The majority number
     */
    int majorityNumber(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;
    }
};

 

解法二:

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: The majority number
     */
    int majorityNumber(vector<int> nums) {
        int res = 0;
        for (int i = 0; i < 32; ++i) {
            int ones = 0, zeros = 0;
            for (int num : nums) {
                if ((num & (1 << i)) != 0) ++ones;
                else ++zeros;
            }
            if (ones > zeros) res |= (1 << i);
        }
        return res;
    }
};

 

[LintCode] Majority Number 求众数

原文:http://www.cnblogs.com/grandyang/p/6068963.html

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