#239 滑动窗口最大值是hard!!!好难的,是我做的第一个hard吧
但这是补的博客,没有仔细分析。复习的时候再仔细总结。
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
//方法一 use priority_queue (max heap)
vector<int> result;
priority_queue<pair<int, int>> maxHeap;
for (int i = 0; i < nums.size(); i++) {
while (!maxHeap.empty() && maxHeap.top().second <= i - k) {
maxHeap.pop();
}
//maxHeap.top().second <= i - k 这里很关键
//第一个窗口结束时,虽然top first确实是最大值3,但是 second是 indx还是0,我们还是会把1弹出
maxHeap.push({nums[i], i});
if (i >= k - 1) {
result.push_back(maxHeap.top().first);
}
}
return result;
}
#347 前 K 个高频元素 Medium
这是补的博客,没有仔细分析。复习的时候再仔细总结。
vector<int> topKFrequent(vector<int>& nums, int k) {
priority_queue<pair<int,int>> maxheap;//cnt,value
sort(nums.begin(),nums.end());
int value=nums[0];
int cnt=0;
for(int i=0;i<nums.size();i++){
if(value==nums[i]){
cnt++;
}
else{
maxheap.push(make_pair(cnt,value));
cnt=1;
value=nums[i];
}
}
maxheap.push(make_pair(cnt,value));
//check
/*
priority_queue<pair<int,int>> tempheap = maxheap;
while (!tempheap.empty()) {
pair<int, int> ele = tempheap.top();
cout << "cnt: " << ele.first << ", value: " << ele.second << endl;
tempheap.pop();
}
*/
vector<int> res;
while(!maxheap.empty() && (k--)){
res.push_back(maxheap.top().second);
maxheap.pop();
}
return res;
}