1、239. 滑动窗口最大值
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/338a12401313c6f9b18623517926edcc.png)
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums.length == 1){
return nums;
}
int len = nums.length-k+1;
int[] res = new int[len];
int num = 0;
MyQueue myQueue = new MyQueue();
for(int i=0;i<k;i++){
myQueue.add(nums[i]);
}
res[num++] = myQueue.peek();
for(int i=k;i<nums.length;i++){
myQueue.poll(nums[i-k]);
myQueue.add(nums[i]);
res[num++] = myQueue.peek();
}
return res;
}
}
class MyQueue{
Deque<Integer> deque = new LinkedList<>();
void poll(int val){
if(!deque.isEmpty() && val == deque.peek()){
deque.poll();
}
}
void add(int val){
while(!deque.isEmpty()&&val>deque.getLast()){
deque.removeLast();
}
deque.add(val);
}
int peek(){
return deque.peek();
}
}
2、347. 前 K 个高频元素
class Solution {
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int num:nums){
map.put(num,map.getOrDefault(num,0)+1);
}
PriorityQueue<int[]> queue = new PriorityQueue<>((o1,o2)->{return o2[1]-o1[1];});
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
queue.add(new int[]{entry.getKey(),entry.getValue()});
}
int[] ans = new int[k];
for(int i=0;i<k;i++){
ans[i] = queue.poll()[0];
}
return ans;
}
}