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   }

  • 相关阅读:
    第一次冲刺结果演示 一组评审总结
    检查博客情况
    第十次站立会议
    第九次站立会议
    暑期实训day4
    暑期实训day3
    暑期实训day2.1——一发空格引发的血案
    暑期实训day2
    暑期实训day1
    黑板模式
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8668453.html
Copyright © 2011-2022 走看看