1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| var a []int
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return a[h.IntSlice[i]] > a[h.IntSlice[j]] }
func (h *hp) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() interface{} { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }
func maxSlidingWindow(nums []int, k int) []int { a = nums q := &hp{make([]int, k)} for i := 0; i < k; i++ { q.IntSlice[i] = i } heap.Init(q)
n := len(nums) ans := make([]int, 1, n-k+1) ans[0] = nums[q.IntSlice[0]] for i := k; i < n; i++ { heap.Push(q, i) for q.IntSlice[0] <= i-k { heap.Pop(q) } ans = append(ans, nums[q.IntSlice[0]]) } return ans }
|