题解 | #最小的K个数#

最小的K个数

https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf

解题思路:使用堆排序

class Solution {
public:
    void HeapAdjust(vector<int> &nums,int i,int heapsize) 
    {
        int left = 2*i+1;
        int right = 2*i+2;
        int smaller = i;
        if(left < heapsize && nums[smaller] >= nums[left])
            smaller = left;
        if(right < heapsize && nums[smaller] >= nums[right])
            smaller = right;
        if(smaller != i)
        {
            int temp = nums[smaller];
            nums[smaller] = nums[i];
            nums[i] = temp;
            HeapAdjust(nums, smaller, heapsize);
        }
    }  
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        int n = input.size();
        for(int i = n/2;i>=0;--i)
            HeapAdjust(input, i, n);
        vector<int> res;
        for(int i = n-1;i>=n-k;--i)
        {
            res.push_back(input[0]);
            swap(input[0],input[i]);
            HeapAdjust(input, 0, i);
        }
        return res;
        
    }
};

全部评论

相关推荐

27届毕业,最近想找一段大厂实习,感觉简历有些问题,好多都不给面,求大佬们指点,最近好焦虑
重生之我学Java干...:我从后端的角度分析一下你的第一个项目,我感觉亮点不是很突出。因为我是因为组内有需求,临时上手学react干活。我用到的技术基本就cover你那个智慧园区管理平台的很多亮点了。那作为比较专业的前端,你上述的内容是不是有点单薄呢。感觉还得包装
点赞 评论 收藏
分享
09-24 18:30
已编辑
长春工业大学 产品经理
小肥罗:HR就是好人的缩写哈哈哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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