您的位置:首页 > 游戏 > 手游 > Golang | Leetcode Golang题解之第218题天际线问题

Golang | Leetcode Golang题解之第218题天际线问题

2024/12/23 7:56:02 来源:https://blog.csdn.net/weixin_66442839/article/details/140223107  浏览:    关键词:Golang | Leetcode Golang题解之第218题天际线问题

题目:

题解:

type pair struct{ right, height int }
type hp []pairfunc (h hp) Len() int            { return len(h) }
func (h hp) Less(i, j int) bool  { return h[i].height > h[j].height }
func (h hp) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v interface{}) { *h = append(*h, v.(pair)) }
func (h *hp) Pop() interface{}   { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }func getSkyline(buildings [][]int) (ans [][]int) {n := len(buildings)boundaries := make([]int, 0, n*2)for _, building := range buildings {boundaries = append(boundaries, building[0], building[1])}sort.Ints(boundaries)idx := 0h := hp{}for _, boundary := range boundaries {for idx < n && buildings[idx][0] <= boundary {heap.Push(&h, pair{buildings[idx][1], buildings[idx][2]})idx++}for len(h) > 0 && h[0].right <= boundary {heap.Pop(&h)}maxn := 0if len(h) > 0 {maxn = h[0].height}if len(ans) == 0 || maxn != ans[len(ans)-1][1] {ans = append(ans, []int{boundary, maxn})}}return
}

版权声明:

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

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