LeetCode239 - 滑动窗口最大值
链接:https://leetcode-cn.com/problems/sliding-window-maximum
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回滑动窗口中的最大值。
示例 1:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[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
示例 2:
输入:nums = [1], k = 1
输出:[1]
示例 3:
输入:nums = [1,-1], k = 1
输出:[1,-1]
示例 4:
输入:nums = [9,11], k = 2
输出:[11]
示例 5:
输入:nums = [4,-2], k = 2
输出:[4]
解法一、使用优先队列维护当前窗口的“值和下标对”,时间复杂度O(nlogn)[说明:每次出入队复杂度logn,操作了n次],空间复杂度O(n)
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums == null || nums.length == 0 || k<1) return new int[0];
// 如果 k >= 数组长度,那么找出数组中的最大值返回
if(k >= nums.length) {
int max = nums[0];
for(int i=1; i< nums.length; i++) {
max = Math.max(nums[i], max);
}
return new int[]{max};
}
// 使用优先队列维护当前窗口的值排序
PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>(){
public int compare(int[] a, int[] b){
return a[0] != b[0]? b[0] - a[0]: b[1] - a[1];
}
});
for(int i=0; i<k; i++) {
queue.offer(new int[]{nums[i], i});
}
int[] result = new int[nums.length - k + 1];
result[0] = queue.peek()[0];
// 滑动
for(int i=1; i< result.length; i++) {
// 滑动进入的元素
int in = nums[i + k -1];
// int out = nums[i];
while(queue.size()>0 && queue.peek()[1] <= i-1) {
queue.poll();
}
queue.offer(new int[]{in, i+k-1});
result[i] = queue.peek()[0];
}
return result;
}
}
解法二、双向队列,双向队列的最左侧元素一定是当前窗口的最大值
时间复杂度O(n),空间复杂度O(k)[说明:因为双向队列里的元素不会大于k个]
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums == null || nums.length == 0 || k<1) return new int[0];
// 如果 k >= 数组长度,那么找出数组中的最大值返回
if(k >= nums.length) {
int max = nums[0];
for(int i=1; i< nums.length; i++) {
max = Math.max(nums[i], max);
}
return new int[]{max};
}
// 双向队列的最左侧元素一定是当前窗口的最大值
// 先初始化双向队列
Deque<Integer> maxValIdxs = new LinkedList<>();
for(int i=0; i<k; i++) {
while(!maxValIdxs.isEmpty() && nums[maxValIdxs.peekLast()] <= nums[i]) {
maxValIdxs.pollLast();
}
maxValIdxs.offerLast(i);
}
int[] result = new int[nums.length - k + 1];
result[0] = nums[maxValIdxs.peekFirst()];
// 滑动
for(int i=1; i<result.length; i++) {
// 滑动进来的元素
int in = nums[k+i-1];
while(!maxValIdxs.isEmpty() && nums[maxValIdxs.peekLast()] <= in){
maxValIdxs.pollLast();
}
maxValIdxs.offerLast(k+i-1);
// 清除滑出的元素
while(maxValIdxs.peekFirst() < i) {
maxValIdxs.pollFirst();
}
result[i] = nums[maxValIdxs.peekFirst()];
}
return result;
}
}