目录
LeetCode 239. 滑动窗口最大值
LeetCode 347.前k个高频元素
LeetCode 239. 滑动窗口最大值
文章讲解:代码随想录
视频讲解:单调队列正式登场!| LeetCode:239. 滑动窗口最大值_哔哩哔哩_bilibili
力扣题目:LeetCode 239. 滑动窗口最大值
代码如下:
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();
}
}
LeetCode 347.前k个高频元素
文章讲解:代码随想录
视频讲解:优先级队列正式登场!大顶堆、小顶堆该怎么用?| LeetCode:347.前 K 个高频元素_哔哩哔哩_bilibili
力扣题目:LeetCode 347.前k个高频元素
代码如下(Java):
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)->pair2[1]-pair1[1]);
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
pq.add(new int[]{entry.getKey(), entry.getValue()});
}
int[] ans = new int[k];
for(int i = 0; i < k; i++){
ans[i] = pq.poll()[0];
}
return ans;
}
}