1 Star 0 Fork 0

Paulden/Algorithm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
get_skyline.go 1.15 KB
一键复制 编辑 原始数据 按行查看 历史
Paulden 提交于 2022-09-11 10:26 . implement skyline
package list
import (
"container/heap"
"sort"
)
// Problem Definition: https://leetcode.cn/problems/the-skyline-problem/
type pair struct {
right, height int
}
type hp []pair
func (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 := 0
h := hp{}
for _, boundary := range boundaries {
for idx < n && buildings[idx][0] <= boundary {
heap.Push(&h, pair{right: buildings[idx][1], height: buildings[idx][2]})
idx++
}
for len(h) > 0 && h[0].right <= boundary {
heap.Pop(&h)
}
maxn := 0
if len(h) > 0 {
maxn = h[0].height
}
if len(ans) == 0 || maxn != ans[len(ans)-1][1] {
ans = append(ans, []int{boundary, maxn})
}
}
return
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/guuzaa/algorithm.git
git@gitee.com:guuzaa/algorithm.git
guuzaa
algorithm
Algorithm
main

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385