Given an array 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.code
Example:rem
Input: nums = [1,3,-1,-3,5,3,6,7], and 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
Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.input
Follow up:
Could you solve it in linear time?it
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { PriorityQueue<Integer> queue = new PriorityQueue<>((i1, i2)->i2-i1); if (nums == null || k == 0 || nums.length < k) return new int[0]; int[] res = new int[nums.length-k+1]; for (int i = 0; i < k; i++) queue.offer(nums[i]); res[0] = queue.peek(); for (int i = k; i < nums.length; i++) { queue.remove(nums[i-k]); queue.offer(nums[i]); res[i-k+1] = queue.peek(); } return res; } }
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || k == 0 || nums.length < k) return new int[0]; int[] res = new int[nums.length-k+1]; int index = 0; Deque<Integer> queue = new ArrayDeque<>(); //queue to save index for (int i = 0; i < nums.length; i++) { //丟棄隊首那些超出窗口長度的元素 index < i-k+1 if (!queue.isEmpty() && queue.peek() < i-k+1) queue.poll(); //隊首的元素都是比後來加入元素大的元素,因此存儲的index對應的元素是從小到大 while (!queue.isEmpty() && nums[queue.peekLast()] < nums[i]) queue.pollLast(); queue.offer(i); if (i >= k-1) res[index++] = nums[queue.peek()]; } return res; } }