1. 题目描述
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
2. 题解
思路:
开辟一个队列,并保证队首始终是当前滑动窗口的最大值,遍历数组,比较当前数组元素和队尾元素的值,如果比队尾元素大就将队尾出队。
细节:
1、队列中应该存储元素的下标,因为元素是可以重复的,下标是唯一的;
2、若队首的下标恰好是上一个窗口的第一个元素的下标时,出队首。
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var maxSlidingWindow = function(nums, k) {
if(nums.length === 1){
return nums;
}
const max = [];
const queue = [];
for(let i = 0; i < nums.length; i++){
//当前队首是上个窗口第一个元素时出队
if(queue.length > 0 && queue[0] === i-k){
queue.shift();
}
//队列不空且队列末尾的值小于当前的i元素
while(queue.length > 0 && nums[queue[queue.length-1]] < nums[i]){
queue.pop();
}
//当前i元素的下标入队
queue.push(i);
//从下标k-1可以有窗口的最大值
if(i >= k-1){
max.push(nums[queue[0]]);
}
}
return max;
};