题目:239. 滑动窗口最大值
给你一个整数数组 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]
提示:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
链接:https://leetcode-cn.com/problems/sliding-window-maximum
解题:
/**
* @author mj
* @date 2021/2/19
*/
public class Z239maxSlidingWindow {
/*
思路:固定滑动窗口算法
*/
public static int[] maxSlidingWindow(int[] nums, int k) {
if (null == nums || nums.length == 1 || k == 1) {
return nums;
}
// 定义窗口指针
int left = 0, right = 0;
int[] res = new int[nums.length - k + 1];
int index = 0;
LinkedList<Integer> list = new LinkedList<>();
while (right < nums.length) {
// 这里的list的首位必须是窗口中最大的那位
while (!list.isEmpty() && nums[right] > list.peekLast()) {
list.removeLast();
}
// 不断添加
list.addLast(nums[right]);
right ++;
// 构造窗口完成,这时候需要根据条件做一些操作
if (right >= k) {
res[index++] = list.peekFirst();
// 如果发现第一个已经在窗口外面了,就移除
if (list.peekFirst() == nums[right - k]) {
list.removeFirst();
}
}
}
return res;
}
public static void main(String[] args) {
int[] nums = new int[]{1,3,-1,-3,5,3,6,7};
int k = 3;
int[] result = maxSlidingWindow(nums, k);
System.out.println(Arrays.toString(result));
// 输出:[3,3,5,5,6,7]
}
/*
滑动窗口算法的代码框架:
非固定大小的滑动窗口,伪码框架:
string s, t;
// 在 s 中寻找 t 的「最小覆盖子串」
int left = 0, right = 0;
string res = s;
while(right < s.size()) {
window.add(s[right]);
right++;
// 如果符合要求,说明窗口构造完成,移动 left 缩小窗口
while (window 符合要求) {
// 如果这个窗口的子串更短,则更新 res
res = minLen(res, window);
window.remove(s[left]);
left++;
}
}
return res;
固定大小的滑动窗口,伪码框架:
// 固定窗口大小为 k
string s;
// 在 s 中寻找窗口大小为 k 时的所包含最大元音字母个数
int right = 0;
while(right < s.size()) {
window.add(s[right]);
right++;
// 如果符合要求,说明窗口构造完成,
if (right>=k) {
// 这是已经是一个窗口了,根据条件做一些事情
// ... 可以计算窗口最大值等
// 最后不要忘记把 right -k 位置元素从窗口里面移除
}
}
return res;
*/
}