上面那个Go语言的有问题,他不能保证一直都是满足小顶堆的限制的,因为push的时候调用的是自己的方法而不是堆的方法,所以不会检测。下面是我写的
type IntHead []int
func (i IntHead) Len() int { return len(i)}
func (In IntHead) Less(i ,j int) bool {
return In[i] < In[j]}
func (In IntHead) Swap(i, j int) {
In[i], In[j] = In[j], In[i]
}
func (In *IntHead) Push(x interface{}) {
*In = append(*In, x.(int))
}
func (In *IntHead) Pop() interface{} {
old := *In
n := len(old)
x := old[n -1]
*In = old[0:n-1]
return x
}
type KthLargest struct {
K int
H *IntHead
}
func Constructor(k int, nums []int) KthLargest {
min := &IntHead{}
heap.Init(min)
kth := KthLargest{K:k, H:min}
for _, num := range nums {
kth.Add(num)
}
return kth
}
func (this *KthLargest) Add(val int) int {
if this.H.Len() == 1 && (*this.H)[0] == 0 && val == -1 {
min := &IntHead{-1,0}
heap.Init(min)
this.H = min
}
if this.H.Len() < this.K {
heap.Push(this.H, val)
} else if (*this.H)[0] < val {
heap.Pop(this.H)
heap.Push(this.H, val)
}
return (*this.H)[0]
}
}
展开