code top push

`

type IntHeap struct {
sort.IntSlice
}

func (h *IntHeap) Push(v interface{}) {
h.IntSlice = append(h.IntSlice, v.(int))
}

func (h *IntHeap) push(v int) {
heap.Push(h, v)
}

func (h *IntHeap) Pop() interface{} {
n := len(h.IntSlice) - 1
num := h.IntSlice[n]
h.IntSlice = h.IntSlice[:n]
return num
}

func (h *IntHeap) pop() int {
return heap.Pop(h).(int)
}

func (h *IntHeap) top() int {
return h.IntSlice[0]
}

func maxEvents(events [][]int) int {
sort.Slice(events, func(i, j int) bool {
if events[i][0] < events[j][0] {
return true
} else {
return false
}
})

ans := 0
hp := &IntHeap{} //小顶堆,存储目前可以参加的所有会议的截止时间
index := 0 // maxEvents遍历到的下标
maxDay := events[0][1] //现在遍历到的最大的会议结束的天数
//i代表今天是第几天
for i := events[0][0]; index < len(events) || i <= maxDay; i++ {
	for ; index < len(events) && events[index][0] == i; index++ {
		if maxDay < events[index][1] {
			maxDay = events[index][1]
		}
		hp.push(events[index][1])
	}
	for hp.Len() > 0 && hp.top() < i {
		hp.pop()
	}
	if hp.Len() != 0 {
		ans++
		hp.pop()
	}
	if index == len(events) && hp.Len() == 0 {
		break
	}
}
return ans

}`

posted @ 2024-03-05 22:52  dx2019  阅读(3)  评论(0编辑  收藏  举报