题解 | #最小的K个数#

最小的K个数

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

top K 问题 大顶堆AC了,没什么难度

        ArrayList<Integer> res = new ArrayList<>();
        if (input.length == 0) return res;
        input = createBigHeap(input);
        for (int i = 0; i < k; i++) {
            res.add(input[i]);
        }
        return res;
    }
    public int[] createBigHeap(int[] nums) {
        //初始化并创建堆,主要想在索引0下找到数组最大值
        int length = nums.length;
        for (int i = (length - 1) / 2; i >= 0; i--) {
            adjustBigHeap(nums, i, length);
        }
        for (int i = length - 1; i >= 0; i--) {
            swap(nums, 0, i);
            adjustBigHeap(nums, 0, i);
        }
        return nums;
    }
    //这里我递归调整了一下
    public void adjustBigHeap(int[] nums, int parent, int length) {
        int pivt = nums[parent];
        int lChild = 2 * parent + 1;
        if (lChild < length) {
            int rChild = lChild + 1;
            int max = lChild;
            if (rChild < length && nums[rChild] > nums[lChild]) max = rChild;
            if (pivt >= nums[max]) return;
            swap(nums, parent, max);
            adjustBigHeap(nums, max, length);
        }
    }
    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
全部评论

相关推荐

2025-12-14 17:54
北京邮电大学 Java
玉字翎:我跟你情况差不多,我选择大三开始每天图书馆待七八个小时,完全不上课,九十月搞完java基础技术栈,十一月投了一整个月简历找到第一份实习,边实习边继续学
你开始找寒假实习了吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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