方法:哈希表
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> res;
unordered_map<int, int> vis;
vis.clear();
for (int i = 0; i < nums.size(); ++i) ++vis[nums[i]];
sort(nums.begin(), nums.end(),[&](const int a, const int b) {
int cnta = vis[a], cntb = vis[b];
if (cnta == cntb) return a < b;
return cnta > cntb;
});
res.push_back(nums[0]);
--k;
for (int i = 1; i < nums.size() && k; ++i) {
if (nums[i] == nums[i-1]) continue;
res.push_back(nums[i]);
--k;
}
return res;
}
};
$时间复杂度O(nlogn),空间复杂度O(k)
方法:单调队列
class Solution {
#define maxn 100010
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
int hh = 0, tt = -1;
int q[maxn];
for (int i = 0; i < nums.size(); ++i) {
if (hh <= tt && i - k + 1 > q[hh]) ++hh;
while (hh <= tt && nums[q[tt]] <= nums[i]) --tt;
q[++tt] = i;
if (i + 1 >= k) res.push_back(nums[q[hh]]);
}
return res;
}
};
$时间复杂度O(n),空间复杂度O(k)