题解 | #最小的K个数#
最小的K个数
https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
//利用golang中collector的包装的heap的push和pop算法
package main
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param input int整型一维数组
* @param k int整型
* @return int整型一维数组
*/
import (
"container/heap"
)
// 实现一个int的heap
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] }
// Push 往堆中插入一个元素
func (h *IntHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
// Pop 从堆中弹出最大的元素
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
*h = old[0 : n-1]
x := old[n-1]
return x
}
func (h *IntHeap) ConvertToInt() []int {
old := *h
return old
}
func GetLeastNumbers_Solution(input []int, k int) []int {
// write code here
if k > len(input) {
return input
}
if k == 0 {
return []int{}
}
topK := &IntHeap{}
heap.Init(topK)
for i := 0; i < k; i++ {
heap.Push(topK, input[i])
}
//后面的元素替换堆中存储的最大元素
for i := k; i < len(input); i++ {
tmp := heap.Pop(topK).(int)
if tmp > input[i] {
heap.Push(topK, input[i])
} else {
heap.Push(topK, tmp)
}
}
return topK.ConvertToInt()
}
查看11道真题和解析