My LeetCode Diary - Day12 Stack&Queue
239. Sliding Window Maximum
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();
}
}
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;
}
}
347. Top K Frequent Elements
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;
}
}