欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Golang | Leetcode Golang题解之第480题滑动窗口中位数

Golang | Leetcode Golang题解之第480题滑动窗口中位数

2024/10/26 17:28:22 来源:https://blog.csdn.net/weixin_66442839/article/details/142932938  浏览:    关键词:Golang | Leetcode Golang题解之第480题滑动窗口中位数

题目:

题解:

type hp struct {sort.IntSlicesize int
}
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 (h *hp) push(v int)         { h.size++; heap.Push(h, v) }
func (h *hp) pop() int           { h.size--; return heap.Pop(h).(int) }
func (h *hp) prune() {for h.Len() > 0 {num := h.IntSlice[0]if h == small {num = -num}if d, has := delayed[num]; has {if d > 1 {delayed[num]--} else {delete(delayed, num)}heap.Pop(h)} else {break}}
}var delayed map[int]int
var small, large *hpfunc medianSlidingWindow(nums []int, k int) []float64 {delayed = map[int]int{} // 哈希表,记录「延迟删除」的元素,key 为元素,value 为需要删除的次数small = &hp{}           // 大根堆,维护较小的一半元素large = &hp{}           // 小根堆,维护较大的一半元素makeBalance := func() {// 调整 small 和 large 中的元素个数,使得二者的元素个数满足要求if small.size > large.size+1 { // small 比 large 元素多 2 个large.push(-small.pop())small.prune() // small 堆顶元素被移除,需要进行 prune} else if small.size < large.size { // large 比 small 元素多 1 个small.push(-large.pop())large.prune() // large 堆顶元素被移除,需要进行 prune}}insert := func(num int) {if small.Len() == 0 || num <= -small.IntSlice[0] {small.push(-num)} else {large.push(num)}makeBalance()}erase := func(num int) {delayed[num]++if num <= -small.IntSlice[0] {small.size--if num == -small.IntSlice[0] {small.prune()}} else {large.size--if num == large.IntSlice[0] {large.prune()}}makeBalance()}getMedian := func() float64 {if k&1 > 0 {return float64(-small.IntSlice[0])}return float64(-small.IntSlice[0]+large.IntSlice[0]) / 2}for _, num := range nums[:k] {insert(num)}n := len(nums)ans := make([]float64, 1, n-k+1)ans[0] = getMedian()for i := k; i < n; i++ {insert(nums[i])erase(nums[i-k])ans = append(ans, getMedian())}return ans
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com