剑指 Offer 59 – I. 滑动窗口的最大值
本问题对应的 leetcode 原文链接:剑指 Offer 59 – I. 滑动窗口的最大值
对应打卡内容:【滑动窗口】剑指 Offer 59 – I. 滑动窗口的最大值
问题描述
给定一个数组 nums
和滑动窗口的大小 k
,请找出所有滑动窗口里的最大值。
示例 :
输入: 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
提示:
你可以假设 k 总是有效的,在输入数组 不为空 的情况下,1 ≤ k ≤ nums.length
。
解题思路
视频讲解直达: 本题视频讲解
代码实现
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums == null || nums.length <= 1){
return nums;
}
LinkedList<Integer> queue = new LinkedList<>();
int[] res = new int[nums.length - k + 1];
int index = 0;
//K
for(int i = 0; i < nums.length; i++){
while(!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]){
queue.pollLast();
}
queue.add(i);
if(queue.peekLast() - k == queue.peek()){
queue.poll();
}
if(i + 1 >= k){
res[index++] = nums[queue.peek()];
}
}
return res;
}
}
时间复杂度:O(n)
额外空间复杂的:O(k)