• 最小的k个数


    题解:

    1. 直接排序,找前面最小的k个
    2. 建立大顶堆,大顶堆,最大的数在最上面嘛。。。

    结果:直接排序比PriorityQueue实现的大顶堆速度更快。。。

     图中8ms的就是直接排序的。

    完整代码:

     1 /**
     2  * @author: wooch
     3  * @create: 2020/02/26
     4  */
     5 
     6 import java.util.Arrays;
     7 import java.util.Comparator;
     8 import java.util.PriorityQueue;
     9 import java.util.Queue;
    10 
    11 /**
    12  * 面试题40. 最小的k个数
    13  * 输入整数数组 arr ,找出其中最小的 k 个数。
    14  * 例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
    15  * 0 <= k <= arr.length <= 1000
    16  * 0 <= arr[i] <= 1000
    17  */
    18 public class P40_GetLeastNumbers {
    19     public int[] getLeastNumbers(int[] arr, int k) {
    20         if (arr.length == k) {
    21             return arr;
    22         }
    23         if (k == 0) {
    24             return new int[0];
    25         }
    26         // int[] res = new int[k];
    27         // Arrays.sort(arr);
    28         // for(int i=0;i<k;i++){
    29         //     res[i]=arr[i];
    30         // }
    31         // return res;
    32 
    33         // Queue<Integer> heap = new PriorityQueue<>(k, (n1, n2) -> n2 - n1);// lambda也可行
    34         Queue<Integer> heap = new PriorityQueue<>(k, new Comparator<Integer>() {
    35             @Override
    36             public int compare(Integer o1, Integer o2) {
    37                 return o2 - o1;
    38             }
    39         });
    40         for (int i = 0; i < arr.length; i++) {
    41             if (heap.size() < k) {
    42                 heap.offer(arr[i]);
    43             } else if (heap.peek() > arr[i]) {
    44                 heap.poll();
    45                 heap.offer(arr[i]);
    46             }
    47         }
    48         int[] res = new int[k];
    49         int i = 0;
    50         while (i < k && !heap.isEmpty()) {
    51             res[i++] = heap.poll();
    52         }
    53         return res;
    54     }
    55 }

    同理,最大的k个数可以排序去后面K个,或者建立小顶堆。

  • 相关阅读:
    写了一个分页控件。
    职业规划
    程序员该做的事
    做就做最优秀的员工
    Tomcat+JSP经典配置实例
    2005年11月26日8点50左右,南昌地震。
    如何添加一个自定义的columnstyles 到设计器中,以便在设计时直接使用他们?
    Oracle 的入门心得【强烈推荐】
    如何随机显示记录条数的15% ?
    重写DataGrid的DataGridBoolColumn,添加bool值改变事件。
  • 原文地址:https://www.cnblogs.com/baishouzu/p/12370079.html
Copyright © 2020-2023  润新知