239. Sliding Window Maximum

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.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

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

Therefore, return the max sliding window as [3,3,5,5,6,7].

一刷
题解:
用一个队列保存index
队首用来移除在范围k之外的元素
队尾用来与新加入的元素比较,如果小于新加入的元素,移除,保证队首的元素是k之内最大的

public class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        int len = nums.length;
        if(len == 0 || k<=0) return new int[0];
        int index = 0;
        int[] res = new int[len - k + 1];
        Deque queue = new ArrayDeque<>();
        
        for(int i=0; i=k-1){
                res[index] = nums[queue.peek()];
                index++;
            }
        }
        return res;
    }
}

二刷同上
一刷的方法非常巧妙

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        Deque q = new ArrayDeque<>(k);
        int len = nums.length;
        if(len == 0 || k == 0) return new int[0];
        int[] res = new int[len - k + 1];

        for(int i=0; i=k-1){
                res[i-k+1] = nums[q.peekFirst()];
            }
        }
        return res;
    }
}

你可能感兴趣的:(239. Sliding Window Maximum)