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   }

 

 

 

posted @ 2018-03-29 10:45  davidnyc  阅读(170)  评论(0)    收藏  举报