1、存在哈希表后,放入vector,对vector用sort
static bool cmp(pair<int, int> a, pair<int, int> b) {
return a.second > b.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
int n = nums.size();
unordered_map<int, int> m;
vector<pair<int, int>> v;
vector<int> res(k);
for (int i = 0; i < n; i++) {
m[nums[i]]++;
}
for (auto itr = m.begin(); itr != m.end(); itr++) {
v.push_back(make_pair(itr->first, itr->second));
sort(v.begin(), v.end(),cmp);
}
for (int i = 0; i < k; i++) {
res[i] = v[i].first;
}
return res;
}
2、用堆选取最大的几个
vector<int> topKFrequent(vector<int>& nums, int k) {
int n = nums.size();
map<int, int> m;
priority_queue<pair<int, int>,vector<pair<int,int>>,greater<pair<int,int>>> v;
vector<int> res(k);
for (int i = 0; i < n; i++) {
m[nums[i]]++;
}
int count = 0;
for (auto itr:m) {
if (count < k) {
v.push(make_pair(itr.second, itr.first));
count++;
}
else if (v.top().first < itr.second) {
v.pop();
v.push(make_pair(itr.second, itr.first));
}
}
for (int i = 0; i < k; i++) {
res[i] = v.top().second;
v.pop();
}
return res;
}
3、利用类似快排的方法
void helper(vector<pair<int, int>>& v, int left, int right, int& k) {
if (right <= left)
return;
pair<int, int> pivot = v[left];
int i = left, j = right;
while (i < j) {
while (i < j && v[j].first < pivot.first) {
j--;
}
if (i < j)
v[i++] = v[j];
while (i < j && v[i].first > pivot.first) {
i++;
}
if (i < j)
v[j--] = v[i];
}
v[i] = pivot;
if (k>i+1) {
helper(v, i+1, right, k);
}
if (k<i) {
helper(v, left, i-1, k);
}
return;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
int n = nums.size();
map<int, int> m;
vector<pair<int,int>> v;
vector<int> res(k);
for (int i = 0; i < n; i++) {
m[nums[i]]++;
}
for (auto itr:m) {
v.push_back(make_pair(itr.second, itr.first));
}
n = v.size();
helper(v, 0, n-1, k);
for (int i = 0; i < k; i++) {
res[i] = v[i].second;
}
return res;
}
最后一种方法很巧妙,但是还是直接用堆又快又好写