题目链接:https://leetcode-cn.com/problems/majority-element-ii/
题目大意:
略。
分析:
k个一起删, 最后check一下即可.
代码如下:
#define foreach(i,c) for (__typeof(c.begin()) i = c.begin(); i != c.end(); ++i)
#define PB push_back
#define ft first
#define sd second class Solution {
public:
vector<int> majorityElement(vector<int>& nums, int k = ) {
vector<int> ans;
unordered_map< int, int > cnt;
int N = nums.size(); for(int i = ; i < N; ++i) {
++cnt[nums[i]];
if(cnt.size() >= k) {
vector< __typeof(cnt.begin()) > toDel; foreach(x, cnt) {
if(--x->sd == ) toDel.PB(x);
} foreach(x, toDel) cnt.erase(*x);
}
} foreach(x, cnt) x->sd = ; for(int i = ; i < N; ++i) {
if(cnt.find(nums[i]) != cnt.end()) ++cnt[nums[i]];
} foreach(x, cnt) {
if(x->sd * k > N) ans.PB(x->ft);
} return ans;
}
};