题解 | #最小的K个数#

最小的K个数

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

package com.hhdd;

import java.util.ArrayList;

/**
 * @Author huanghedidi
 * @Date 2024/3/20 21:36
 */
public class 最小的K个数 {
    public static ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
        // write code here
        if (k == 0) {
            return new ArrayList<Integer>();
        }
        makeHeap(input);
        ArrayList<Integer> res = new ArrayList<>(k);
        for (int i = 0; i < k; i++) {
            res.add(input[0]);
            // 交换顺序,然后调整堆
            int tmp = input[0];
            input[0] = input[input.length - 1 - i];
            input[input.length - 1 - i] = tmp;
            adjust(input, input.length - 1 - i - 1);
        }
        return res;
    }

    // 成堆
    public static void makeHeap(int[] input) {
        for (int i = 1; i < input.length; i++) {
            int cur = i;
            while (input[cur] < input[(cur - 1) / 2]) {
                int tmp = input[cur];
                input[cur] = input[(cur - 1) / 2];
                input[(cur - 1) / 2] = tmp;
                cur = (cur - 1) / 2;
            }
        }
    }

    public static void adjust(int[] input, int end) {
        int cur = 0;
        while (cur <= end) {
            int left = cur * 2 + 1;
            int smallest = cur;
            if (left <= end) {
                smallest = input[cur] > input[left] ? left : cur;
                int right = left + 1;
                if (right <= end) {
                    smallest = input[smallest] > input[right] ? right : smallest;
                }
            }
            if (smallest == cur) {
                break;
            }
            int tmp = input[cur];
            input[cur] = input[smallest];
            input[smallest] = tmp;
            cur = smallest;
        }
    }

    public static void main(String[] args) {
        int[] input = new int[]{0, 1, 1, 1, 4, 5, 3, 7, 7, 8, 10, 2, 7, 8, 0, 5, 2, 16, 12, 1, 19, 15, 5, 18, 2, 2, 22, 15, 8, 22, 17, 6, 22, 6, 22, 26, 32, 8, 10, 11, 2, 26, 9, 12, 9, 7, 28, 33, 20, 7, 2, 17, 44, 3, 52, 27, 2, 23, 19, 56, 56, 58, 36, 31, 1, 19, 19, 6, 65, 49, 27, 63, 29, 1, 69, 47, 56, 61, 40, 43, 10, 71, 60, 66, 42, 44, 10, 12, 83, 69, 73, 2, 65, 93, 92, 47, 35, 39, 13, 75};
        ArrayList<Integer> res = GetLeastNumbers_Solution(input, 75);
        System.out.println(res);
    }

}

全部评论

相关推荐

一个菜鸡罢了:哥们,感觉你的简历还是有点问题的,我提几点建议,看看能不能提供一点帮助 1. ”新余学院“别加粗,课程不清楚是否有必要写,感觉版面不如拿来写一下做过的事情,教育经历是你的弱势就尽量少写 2. “干部及社团经历”和“自我评价”删掉 3. 论文后面的“录用”和“小修”啥的都删掉,默认全录用,问了再说,反正小修毕业前肯定能发出来 4. 工作经验和研究成果没有体现你的个人贡献,着重包装一下个人贡献
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务