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.java
Return the max sliding window.數組
Example 1:code
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [3,3,5,5,6,7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
Example 2:隊列
Input: nums = [1], k = 1 Output: [1]
Example 3:it
Input: nums = [1,-1], k = 1 Output: [1,-1]
Example 4:io
Input: nums = [9,11], k = 2 Output: [11]
Example 5:ast
Input: nums = [4,-2], k = 2 Output: [4]
Constraints:class
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
1 <= k <= nums.length
給定一個數組和一個定長窗口,將窗口在數組上從左到右滑動,記錄每一步在當前窗口中的最大值。遍歷
優先隊列im
維護一個優先隊列,存儲一個數值對(nums[index], index)。遍歷數組,計算當前窗口的左邊界left,將當前數字加入到優先隊列中,查看當前優先隊列中的最大值的下標是否小於left,若是是則說明該最大值不在當前窗口中,出隊,重複操做直到最大值在當前窗口中,並加入結果集。
雙向隊列
維護一個雙向隊列,存儲下標。遍歷數組,計算當前窗口的左邊界left,若是隊首元素小於left則出隊;接着從隊尾開始,將全部小於當前元素的下標依次出隊,最後將當前下標入隊。這樣能保證每次剩下的隊首元素都是當前窗口中的最大值。
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { int[] ans = new int[nums.length - k + 1]; Queue<int[]> q = new PriorityQueue<>((a, b) -> b[0] - a[0]); int left = 0; for (int i = 0; i < nums.length; i++) { left = i - k + 1; q.offer(new int[]{nums[i], i}); if (left >= 0) { while (q.peek()[1] < left) { q.poll(); } ans[left] = q.peek()[0]; } } return ans; } }
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { int[] ans = new int[nums.length - k + 1]; Deque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < nums.length; i++) { int left = i - k + 1; if (!q.isEmpty() && q.peekFirst() < left) { q.pollFirst(); } while (!q.isEmpty() && nums[i] > nums[q.peekLast()]) { q.pollLast(); } q.offerLast(i); if (left >= 0) { ans[left] = nums[q.peekFirst()]; } } return ans; } }