239. 滑动窗口最大值
- 根据题意,i为nums下标,是要在[i - k + 1, i] 中选到最大值,只需要保证两点
- 1.队列头结点需要在[i - k + 1, i]范围内,不符合则要弹出队列开头
- E.g. nums = [1,3,-1,-3,5,3,2,1] deque = [1,3,-1] 现在要更新下一个窗口,要把1去掉(1的index为0,i现在为3,3-0>=3),加-3
- 2.既然是单调,就要保证每次放进去的数字要比末尾的都大,否则也弹出队列结尾
- 因为单调,当i增长到符合第一个k范围的时候,每滑动一步都将队列头节点放入结果就行了
-
Time complexity : O(N), since each element is processed exactly twice - it's index added and then removed from the deque.
-
Space complexity : O(N), since O(N−k+1) is used for an output array and O(k) for a deque.
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
Deque<Integer> deque = new ArrayDeque<Integer>();
int[] ans = new int[nums.length-k+1];
for (int i=0; i<nums.length; i++) {
int start = i-k+1;
while (!deque.isEmpty() && i-deque.peekFirst()>=k)
deque.pollFirst();
while (!deque.isEmpty() && nums[i]>nums[deque.peekLast()])
deque.pollLast();
deque.addLast(i);
if (start >= 0) ans[start] = nums[deque.peekFirst()];
}
return ans;
}
}
347.前 K 个高频元素
- 方法1: 用小根堆,出现频率低的在前面
Queue<Integer> q = new PriorityQueue<> ((a,b)->map.get(a)-map.get(b));
- heap.size()>=k 弹出最前面的(频率最少的)
-
Time complexity : O(Nlogk) if k<N and O(N) in the particular case of N=k. That ensures time complexity to be better than O(NlogN).
-
Space complexity : O(N+k) to store the hash map with not more N elements and a heap with k elements.
class Solution {
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int num: nums) {
map.put(num, map.getOrDefault(num, 0)+1);
}
Queue<Integer> q = new PriorityQueue<> ((a,b)->map.get(a)-map.get(b));
for (Integer key: map.keySet()) {
q.add(key);
if (q.size() > k) {
q.poll();
}
}
int[] ans = new int[k];
int i=k;
while (!q.isEmpty()) {
ans[--i] = q.poll();
}
return ans;
}
}