[LintCode] Majority Number 求众数

Posted Grandyang

tags:

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

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 求众数的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-medium-Majority Number III

Lintcode046.Majority Number

[LintCode] Majority Number 求众数

Majority Number

169. Majority Element

Leetcode 169. Majority Element