Problem Description:
Given an array nums, a sliding window of size k moves from the leftmost side of the array to the rightmost side of the array. You can only see the k numbers in the sliding window. The sliding window only moves one position to the right at a time.
Returns the maximum value in the sliding window.
Advanced:
Can you solve this problem in linear time complexity?
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
The position of the sliding window Maximum value
--------------- ----
[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
prompt:
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
1 <= k <= nums.length
Source: LeetCode
Link: https://leetcode-cn.com/problems/sliding-window-maximum
Solutions
Double pointer traversal
/*
*作者:赵星海
*时间:2020/9/14 10:36
*用途:滑动窗口最大值
*/
public int[] maxSlidingWindow(int[] nums, int k) {
//通过模拟k==1和k==3 得出结果的长度为nums.length+1-k
int[] result = new int[nums.length + 1 - k];
for (int i = 0; i < nums.length + 1 - k; i++) {
int x = nums[i];
for (int j = i + 1; j < (i + k); j++) {
if (nums[j] > x) {
x = nums[j];
}
}
result[i] = x;
}
return result;
}