Array: smallest number K

Title Description

Input n integers, find the smallest number K. 4,5,1,6,2,7,3,8 e.g. eight digital inputs, the minimum number is four 1,2,3,4 ,.

Problem-solving ideas

Two ways:

Method 1: First to sort the array, and then removed before the k values;

Method 2: Use the maximum heap save this number k, and each time than the top of the heap, if only smaller than the top of the heap, remove the top of the heap, the new number into the heap.

Reference Code

Method 1: Run time: 29ms take up memory: 9576k

 1 import java.util.Arrays;
 2 import java.util.ArrayList;
 3 public class Solution {
 4     public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
 5         ArrayList<Integer> res = new ArrayList<Integer>();
 6         if(input == null || k ==0 || k > input.length) {
 7             return res;
 8         }
 9         Arrays.sort(input);
10         for(int i = 0; i < k; i++) {
11             res.add(input[i]);
12         }
13         return res;
14     }
15 }
View Code

Method 2:

 1 import java.util.ArrayList;
 2 import java.util.PriorityQueue;
 3 import java.util.Comparator;
 4 public class Solution {
 5     public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
 6         ArrayList<Integer> res = new ArrayList<Integer>();
 7         if(input == null || k ==0 || k > input.length)
 8             return res;
 9         PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>() { 
10             public int compare(Integer e1, Integer e2) {
11                 return e2 - e1;
12             }
13         });
14         for(int i=0; i<input.length; i++){
15             if(maxHeap.size() != k)
16                 maxHeap.offer(input[i]);
17             else{
18                 if(maxHeap.peek() > input[i]){
19                     maxHeap.poll();
20                     maxHeap.offer(input[i]);
21                 }
22             }
23         }
24         for(Integer i: maxHeap){
25             res.add(i);
26         }
27         return res;
28     }
29 }
View Code

 

Guess you like

Origin www.cnblogs.com/carry6/p/11518544.html