题解 | #最小的K个数#

最小的K个数

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

public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        
        if (k == 0) {
            return new ArrayList<>();
        }
        int length = input.length;
        for (int i = length / 2 - 1; i >= 0; --i) {
            adjustHeap(input, i, length);
        }

        ArrayList<Integer> result = new ArrayList<>();
        for (int i = length - 1; i >= 0; --i) {

            int minValue = input[0];
            input[0] = input[i];
            input[i] = minValue;

            result.add(minValue);
            if (result.size() >= k) {
                break;
            }
            adjustHeap(input, 0, i);
        }
        return result;
    }

    private void adjustHeap(int[] array, int parent, int length) {

        int temp = array[parent];
        int child = 2 * parent + 1;

        while (child < length) {

            if (child + 1 < length && array[child] > array[child + 1]) {
                ++child;
            }

            if (temp <= array[child]) {
                break;
            }

            array[parent] = array[child];
            parent = child;
            child = 2 * child + 1;
        }

        array[parent] = temp;
    }

全部评论

相关推荐

头顶尖尖的程序员:我也是面了三四次才放平心态的。准备好自我介绍,不一定要背熟,可以记事本写下来读。全程控制语速,所有问题都先思考几秒,不要急着答,不要打断面试官说话。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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