有一个整型数组arr和一个大小为n的窗口从数组的最左边滑动到最右边,窗口每次向右边滑动一个位置。
例如,数组为[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 窗口中最大值为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
如果数值长度为m,窗口大小为n,则一共生成m-n+1个窗口的最大值。实现一个函数。
输入:整型数组arr,窗口大小为n.
输出:一个长度为m-n+1的数组ans,ans[i]表示每一种窗口状态下的最大值。
以本案例为例,结果应返回{3,3,5,5,6,7}
func maxSlidingWindow(nums []int, k int) []int {
q := []int{}
push := func(i int) {
for len(q) > 0 && nums[i] >= nums[q[len(q)-1]] {
q = q[:len(q)-1]
}
q = append(q, i)
}
for i := 0; i < k; i++ {
push(i)
}
n := len(nums)
ans := make([]int, 1, n-k+1)
ans[0] = nums[q[0]]
for i := k; i < n; i++ {
push(i)
for q[0] <= i-k {
q = q[1:]
}
ans = append(ans, nums[q[0]])
}
return ans
}