LintCode Majority Number II / III
Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.
Find it.
Have you met this question in a real interview? Yes
Example
Given [1, 2, 1, 2, 1, 3, 3], return 1.
Note
There is only one majority number in the array.
Challenge
O(n) time and O(1) extra space.
既然已经到1/3了不如直接用1/K的做法:
class Solution {
public:
/**
* @param nums: A list of integers
* @return: The majority number occurs more than 1/3.
*/
int majorityNumber(vector<int> nums) {
// write your code here
int stored = 2;
unordered_map<int, int> counts;
for (int e : nums) {
if (counts.size() < stored && counts.count(e) == 0) {
counts[e] = 1;
continue;
}
if (counts.count(e) == 0) {
auto iter = counts.begin();
while (iter != counts.end()) {
if (--iter->second == 0) {
iter = counts.erase(iter);
continue;
}
++iter;
}
} else {
counts[e]++;
}
}
int maxcount = -1;
int majority = 0;
for (auto& iter : counts) {
iter.second = 0;
}
for (int e : nums) {
if (counts.count(e)) {
if (++counts[e] > maxcount) {
maxcount = counts[e];
majority = e;
}
}
}
return majority;
}
};
当K=3时,由于数组中总是有数字会超过1/3个,那么我们三个一组三个一组的把(不同)数字依次除去,剩下可能又1个、2个数字的情况,当剩下数字只有一个时该数就是所求的数字,当有两个时我们是不能确定的,需要看已除去组中那个数字出现的比较多才能决定。
算法就是使用哈希来存储K-1个不同数字出现的次数,当有一个数和哈希表中任意K-1一个数都不同时,可以将这K个数作为一组整体划去(两两不同的一组数),体现为将K-1个数的计数减一(因为刚刚那个和K-1数都不同的数并没有存储到哈希表中所以不需要额外动作)。当划去过程中某个数在哈希表中计数值到达零时应该将其删去。最后再对留在哈希表中的数字做一个统计看到底那个数出现的次数多。
因而空间复杂度可以认为是O(K)的
*/
int majorityNumber(vector<int> nums, int k) {
// write your code here
int stored = k - 1;