LeetCode 239. Sliding Window Maximum
Solution:
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 idx = 0;
MyQueue myQueue = new MyQueue();
// Put the first k elements into the myQueue
for(int i=0; i<k; i++)
myQueue.add(nums[i]);
res[idx++] = myQueue.peek();
for(int i = k; i < nums.length; i++){
myQueue.poll(nums[i-k]); // remove the front element
myQueue.add(nums[i]); // add the following element
res[idx++] = myQueue.peek(); // record the max value
}
return res;
}
}
class MyQueue{
Deque<Integer> deque = new LinkedList<>();
// When removing the front element, we must judge whether the element to be removed is equal to the front element of the window.
void poll(int val){
if(!deque.isEmpty() && deque.peek() == val)
deque.poll();
}
void add(int val){
// If the element to add is larger than the entrance element, remove the entrance element.
while(!deque.isEmpty() && deque.getLast() < val)
deque.pollLast();
deque.add(val);
}
int peek(){
return deque.peek();
}
}
Thoughts:
- When removing the front element, we must judge whether the element to be removed is equal to the front element of the window.
- If the element to add is larger than the entrance element, remove the entrance element.
LeetCode 347. Top K Frequent Elements
Solution:
// 1、Build hash map : character and how often it appears
Map<Integer, Integer> map = new HashMap<>();
for(int n : nums)
map.put(n, map.getOrDefault(n, 0) + 1);
// 2、Order the frequencies, the less frequent element first
// diy a comparator
Queue<Integer> heap = new PriorityQueue<>((n1,n2) -> map.get(n1) - map.get(n2));
for(Integer key : map.keySet()){
heap.add(key);
if(heap.size() > k)
heap.poll();
}
// 3. Build an output array, from small to large
int[] top = new int[k];
for(int i = k-1; i >= 0 ; i--)
top[i] = heap.poll();
return top;
Thought:
- 1、Build hash map : character and how often it appears
- 2、Order the frequencies by
min-heap
, the less frequent element first - 3、 Build an output array, from small to large