[LintCode] Majority Number 求大多数

时间:2023-03-10 04:27:07
[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.

Have you met this question in a real interview?
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 = , cnt = ;
for (int num : nums) {
if (cnt == ) {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 = ;
for (int i = ; i < ; ++i) {
int ones = , zeros = ;
for (int num : nums) {
if ((num & ( << i)) != ) ++ones;
else ++zeros;
}
if (ones > zeros) res |= ( << i);
}
return res;
}
};