zoukankan      html  css  js  c++  java
  • 最小的K个数

    最小的K个数

    输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

    代码实现

    package 剑指offer;

    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.PriorityQueue;

    /**
     * @author WangXiaoeZhe
     * @Date: Created in 2019/11/22 17:06
     * @description:
     */

    public class Main14 {
        public static void main(String[] args) {

        }

        public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
            ArrayList<Integer> list = new ArrayList<>();
            int len = input.length;
            /**
             * 不符合条件返回为空
             */

            if (len < k || len < 1 || k == 0) {
                return list;
            }
            /**
             * 构建大顶堆
             */

            PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return o2 - o1;
                }
            });

            /**
             * 构建为K的大顶堆
             */

            for (int i = 0; i < len; i++) {
                if (maxHeap.size() != k) {
                    maxHeap.offer(input[i]);
                }else if (maxHeap.peek()>input[i]){
                    maxHeap.poll();
                    maxHeap.offer(input[i]);
                }
            }
            for (Integer integer : maxHeap) {
                list.add(integer);
            }
            return list;

        }

    }
  • 相关阅读:
    形态学权重图像去噪
    druid配置
    @mapper个人理解
    mybatis自动生成的bean接口在service层找不到
    type-aliases-package的作用
    windows查询端口是否被占用
    idea中使用lombok注解无效
    springboot+dubbo问题记录
    springboot跳转到其他controller
    BigDecimal做减法计算
  • 原文地址:https://www.cnblogs.com/wuhen8866/p/11913113.html
Copyright © 2011-2022 走看看