1 215. 数组中的第K个最大元素
时间复杂度要O(n)所以用了hash,空间换时间,ac代码:
class Solution {
public:
int a[20010];
int findKthLargest(vector<int>& nums, int k) {
// hash
int min = INT_MAX;
int max = INT_MIN;
for(auto x : nums)
{
a[x + 10000]++;
if(x+1e4 > max)max = x + 1e4;
if(x+1e4 < min)min = x + 1e4;
}
int cnt = 0;
for(int i = max ; i >= min; i--)
{
cnt += a[i];
if(cnt >= k)
return i-1e4;
}
return 0;
}
};
看了题解,忘了一个叫快速选择的东西:
todo
2 347. 前 K 个高频元素
这次我用了map 之后转成vector排序,其实可以优先队列排序,见我的sxl题解
class Solution {
public:
static bool cmp(pair<int,int> a,pair<int,int> b)
{
return a.second > b.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
// map
map<int,int> mp;
for(auto u : nums)
mp[u]++;
vector<pair<int,int>> tmp(mp.begin(),mp.end());
sort(tmp.begin(),tmp.end(),cmp);
vector<int> ans;
for(int i = 0; i < k; i++)
ans.push_back(tmp[i].first);
return ans;
}
};