-
Notifications
You must be signed in to change notification settings - Fork 257
/
majority-number-ii.cpp
56 lines (49 loc) · 1.61 KB
/
majority-number-ii.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param nums: A list of integers
* @return: The majority number occurs more than 1/3.
*/
int majorityNumber(vector<int> nums) {
const int k = 3;
unordered_map<int, int> hash;
for (const auto& i : nums) {
++hash[i];
// Detecting k items in hash, at least one of them must have exactly
// one in it. We will discard those k items by one for each.
// This action keeps the same mojority numbers in the remaining numbers.
// Because if x / n > 1 / k is true, then (x - 1) / (n - k) > 1 / k is also true.
if (hash.size() == k) {
auto it = hash.begin();
while (it != hash.end()) {
if (--(it->second) == 0) {
hash.erase(it++);
} else {
++it;
}
}
}
}
// Resets hash for the following counting.
for (auto& it : hash) {
it.second = 0;
}
// Counts the occurrence of each candidate word.
for (const auto& i : nums) {
auto it = hash.find(i);
if (it != hash.end()) {
++it->second;
}
}
// Selects the integer which occurs > n / k times.
vector<int> ret;
for (const pair<int, int>& it : hash) {
if (it.second > static_cast<double>(nums.size()) / k) {
ret.emplace_back(it.first);
}
}
return ret[0];
}
};