题目链接:239. 滑动窗口最大值 - 力扣(LeetCode)
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums.length == 1){
return nums;
}
MyQueue queue = new MyQueue();
int[] result = new int[nums.length - k + 1];
for(int i = 0; i < k; i ++){
queue.add(nums[i]);
}
int number = 0;
result[number ++] = queue.peek();
for(int i = k; i < nums.length; i ++){
queue.poll(nums[i - k]);
queue.add(nums[i]);
result[number ++] = queue.peek();
}
return result;
}
}
class MyQueue{
Deque<Integer> deque = new LinkedList<>();
void poll(int val){
if(!deque.isEmpty() && deque.peek() == val){
deque.poll();
}
}
void add(int val){
while(!deque.isEmpty() && val > deque.getLast()){
deque.removeLast();
}
deque.add(val);
}
int peek(){
return deque.peek();
}
}
尤其注意poll元素的时候,该元素什么时候出队列
题目链接:347. 前 K 个高频元素 - 力扣(LeetCode)
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int num: nums){
map.put(num, map.getOrDefault(num,0) + 1);
}
PriorityQueue<int[]> pq = new PriorityQueue<>((pair1, pair2) -> pair1[1] - pair2[1]);
for(Map.Entry<Integer, Integer> entry: map.entrySet()){
if(pq.size() < k){
pq.add(new int[]{entry.getKey(), entry.getValue()});
}else if(entry.getValue() > pq.peek()[1]){
pq.poll();
pq.add(new int[]{entry.getKey(), entry.getValue()});
}
}
int[] result = new int[k];
for(int i = k - 1; i >= 0; i --){
result[i] = pq.poll()[0];
}
return result;
}
}
小顶堆的应用,比快排要快一些