题解 | #最小的K个数#
最小的K个数
https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
package main import "container/heap" /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param input int整型一维数组 * @param k int整型 * @return int整型一维数组 */ func GetLeastNumbers_Solution( input []int , k int ) []int { if k == 0 || len(input) == 0 { return []int{} } h := &IntHeap{} heap.Init(h) for i := 0; i < k; i++ { heap.Push(h, input[i]) } for i := k; i < len(input); i++ { if input[i] < (*h)[0] { heap.Pop(h) heap.Push(h, input[i]) } } return *h } type IntHeap []int func (h IntHeap) Len() int { return len(h) } func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] } func (h IntHeap) Swap(i,j int) { h[i],h[j] = h[j],h[i] } func (h *IntHeap) Push (x interface{}) { *h = append(*h, x.(int)) } func (h *IntHeap) Pop () interface{} { old := *h n := len(old) x := old[n-1] *h = old[0:n-1] return x }