LeetCode讲解篇之239. 滑动窗口最大值-题解代码

时间:2024-10-07 07:36:18
func maxSlidingWindow(nums []int, k int) []int {
    st := [][2]int{[2]int{0, nums[0]}}

    ans := make([]int, 0, len(nums) - k + 1)

    for i := 1; i < k; i++ {
        for len(st) > 0 && st[len(st) - 1][1] < nums[i] {
            st = st[:len(st) - 1]
        }
        st = append(st, [2]int{i, nums[i]})
    }

    ans = append(ans, st[0][1])

    for i := k; i < len(nums); i++ {
        for len(st) > 0 && st[len(st) - 1][1] < nums[i] {
            st = st[:len(st) - 1]
        }
        st = append(st, [2]int{i, nums[i]})

        if i - st[0][0] == k {
            st = st[1:]
        }

        ans = append(ans, st[0][1])
    }

    return ans
}