在数组中找到出现次数大于n/k的数

这道题十分重要,有诸多解法,且用到许多不同的思想。

在数组中找到出现次数超过n/2的数

暴力破解

排序法

在数组找到出现次数大于n/k的数

在数组中找到出现次数大于n/3的数

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
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> res;
if(nums.empty()){
return res;
}
map<int, int> mp; // cand
for(int i=0;i<nums.size();i++){
if(mp.find(nums[i]) == mp.end()){
mp[nums[i]] = 1;
}else{
++mp[nums[i]];
}
if(mp.size() == 3){
allMinusOne(mp);
}
}
map<int,int> counter;
countElem(nums, mp, counter);
for(auto it=mp.begin();it!=mp.end();it++){
int num = it->first;
if(counter[num]>(nums.size()/3)){
res.push_back(num);
}
}
return res;
}
void allMinusOne(map<int,int> &mp){
auto it= mp.begin();
while(it!=mp.end()){
if(it->second==1){
it = mp.erase(it);
}else{
--it->second;
it++;
}
}
}
void countElem(vector<int>& nums, map<int,int>& mp,map<int,int>& counter){
for(auto num:nums){
if(mp.find(num)!=mp.end()){
if(counter.find(num)==counter.end()){
counter[num] = 1;
}else{
++counter[num];
}
}
}
}
};

c++中map的find方法查找一个键的时间复杂度为O(logn)