题解 | #最小的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
}




全部评论

相关推荐

小浪_Coding:1. 个人技能排版太乱, 写的技术栈太浅了, 跟测试,自动化相关的太少; 2. 项目开发类的太简单没有亮点, 算法类的项目建议只放一个,最好有自动化,CI/CD, pipline的项目, 需要更换; 3.整体排版需要优化, SOOB打招呼都需要注意等.
我的简历长这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务