zoukankan      html  css  js  c++  java
  • LF.25.K Smallest In Unsorted Array

    Find the K smallest numbers in an unsorted integer array A. The returned numbers should be in ascending order.

    Assumptions

    A is not null
    K is >= 0 and smaller than or equal to size of A
    Return

    an array with size K containing the K smallest numbers in ascending order
    Examples

    A = {3, 4, 1, 2, 5}, K = 3, the 3 smallest numbers are {1, 2, 3}

     1 public int[] kSmallest(int[] array, int k) {
     2     // Write your solution here
     3     int[] res = minHeap(array, k);
     4     return res ;
     5 
     6   }
     7   //method 1: min heap
     8   private int[] minHeap(int[] array, int k){
     9     int[] res = new int[k] ;
    10     //this is the priority queue
    11     Queue<Integer> queue = new PriorityQueue<Integer>() ;
    12     //step1 : offer all items in the queue
    13     for (int i=0; i<array.length ; i++) {
    14         queue.offer(array[i]);
    15     }
    16     //step 2, poll the k items out
    17     for (int i=0; i<k; i++) {
    18         int value = queue.poll();
    19         res[i] = value;
    20     }
    21     return res ;
    22   }

  • 相关阅读:
    create joint
    delphi 使用parent让进度条上显示文字
    abSymMeshMEL.txt
    ini写配置信息
    CreateBindGroupNode.txt
    CreateaJointCurve.txt
    09 IKFKMatch.txt
    TIF_to_MAP.BAT
    ImportBVHv20.txt
    FormatDateTime 一段以时间为命令的代码
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8668453.html
Copyright © 2011-2022 走看看