239. Sliding Window Maximum
Link: https://leetcode.com/problems/sliding-window-maximum/
Description
You are given an array of integers nums
, there is a sliding window of size k
which is moving from the very left of the array to the very right. You can only see the k
numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
Approach
Monotonic Queue
We want to design a queue that the numbers in the queue are sorted in descending order. As we only care about the max number of size k. This array only needs to maintain at most k numbers.
- Initialize a ArrayDeque
queue
, a int arrayresult
. - For
n
innums
:- If the
queue
is not empty and containsk
numbers, the top of thequeue
equals ton
, remove the top of thequeue
. - While the last item of
queue
less thann
, remove the last item iteratively until thequeue
is empty or the last item greater than or equal ton
. - Add
n
to thequeue
. - If
n >= k - 1
, add the top of thequeue
to result.
- If the
Solution
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
ArrayDeque<Integer> queue = new ArrayDeque<>();
int[] result = new int[nums.length - k + 1];
for (int i = 0; i < nums.length; i++) {
if (!queue.isEmpty() && i - k >= 0 && queue.peek() == nums[i - k])
queue.remove();
while (!queue.isEmpty() && queue.peekLast() < nums[i])
queue.removeLast();
queue.add(nums[i]);
if (i >= k - 1)
result[i - k + 1] = queue.peek();
}
return result;
}
}
347. Top K Frequent Elements
Link: https://leetcode.com/problems/top-k-frequent-elements/
Description
Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
Approach
Priority Queue
- Initialize a map to collect the numbers and their frequencies.
- Initialize a priority queue of ascending order.
- Add the entries of map to the queue, if the size of the queue larger than k, pop the top of the queue.
Solution
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
int[] result = new int[k];
for (int n: nums)
map.put(n, map.getOrDefault(n, 0) + 1);
PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> (o1[1] - o2[1]));
for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
pq.add(new int[]{entry.getKey(), entry.getValue()});
if (pq.size() > k)
pq.remove();
}
for (int i = 0; i < k; i++)
result[i] = pq.remove()[0];
return result;
}
}
Reference: https://programmercarl.com/