funcmain() { var n, k int fmt.Scanln(&n, &k) list := make([]int, n) for i := 0; i < n; i++ { fmt.Scan(&list[i]) } max, min := slidingWindow(list, k) // 直接for循环输出也可 fmt.Println(strings.Trim(fmt.Sprint(min), "[]")) fmt.Println(strings.Trim(fmt.Sprint(max), "[]")) }
funcslidingWindow(list []int, k int) (max, min []int) { var maxWindow, minWindow []int // 单调递减队列 maxPush := func(i int) { forlen(maxWindow) > 0 && list[maxWindow[len(maxWindow)-1]] < list[i] { maxWindow = maxWindow[:len(maxWindow)-1] } maxWindow = append(maxWindow, i) } // 单调递增队列 minPush := func(i int) { forlen(minWindow) > 0 && list[minWindow[len(minWindow)-1]] > list[i] { minWindow = minWindow[:len(minWindow)-1] } minWindow = append(minWindow, i) } for i := 0; i < k; i++ { maxPush(i) minPush(i) } max = append(max, list[maxWindow[0]]) min = append(min, list[minWindow[0]]) for i := k; i < len(list); i++ { maxPush(i) minPush(i) // 删除超出窗口的部分 for maxWindow[0] < i-k+1 { maxWindow = maxWindow[1:] } for minWindow[0] < i-k+1 { minWindow = minWindow[1:] } max = append(max, list[maxWindow[0]]) min = append(min, list[minWindow[0]]) } return }