Leetcode 0239: Sliding Window Maximum

题目描述:

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.

Example 1:

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:

Input: nums = [1,-1], k = 1
Output: [1,-1]

Example 4:

Input: nums = [9,11], k = 2
Output: [11]

Example 5:

Input: nums = [4,-2], k = 2
Output: [4]

Constraints:

1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length

Time complexity: O(n)
Space complexity: O(k)
当我们移动滑动窗口时,如果当前的滑动窗口中有两个下标 i 和 j,其中 i 在 j的左侧(i < j),并且 i 对应的元素不大于 j 对应的元素nums[i] <= nums[j]. 当滑动窗口向右移动时,只要 i 还在窗口中,那么 j一定也还在窗口中,这是 i 在 j 的左侧所保证的。因此,由于 nums[i] <= nums[j]. 的存在,nums[i]一定不会是滑动窗口中的最大值了,我们可以将 nums[i]永久地移除。

  1. 使用双端队列Deque存储所有还没有被移除的下标。在队列中,这些下标按照从小到大的顺序排列,且它们在数组nums 中对应的值是严格单调递减的。因为根据上面的分析如果i 在 j的左侧(i < j),且对应的元素nums[i] <= nums[j]. 则i就会被移除。
  2. 当滑动窗口向右移动时,队列加入新元素。为了保持队列单调递减的性质,不断地将新元素与队尾的元素相比较,如果新元素较大,那么将队尾的元素弹出队列。不断地进行此项操作,直到队列为空或者新的元素小于队尾的元素。
  3. 此时队首下标对应的元素就是滑动窗口中的最大值。随着窗口向右移动,滑动窗口size越界是,还需要不断从队首弹出元素,直到队首元素在窗口中为止。

为了可以同时弹出队首和队尾的元素,我们需要使用双端队列。满足这种单调性的双端队列一般称作「单调队列」。

class Solution {
    
    
    public int[] maxSlidingWindow(int[] nums, int k) {
    
    
        if(nums == null || nums.length < 2) return nums;
        int n = nums.length;
        int[] res = new int[n-k+1];
        Deque<Integer> queue = new ArrayDeque<>();
        for(int i = 0; i < n;i++){
    
    
            while(!queue.isEmpty() && nums[queue.peekLast()] < nums[i]){
    
    
                queue.pollLast();
            }
            queue.addLast(i);
            if(queue.peekFirst() <= i-k){
    
    
                queue.poll();  
            }
            if(i >= k-1){
    
    
                res[i-k+1] = nums[queue.peek()];
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113987140