数组:最小的K个数

题目描述

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

解题思路

两种方法:

法1:先对数组排序,然后取出前k个值;

法2:利用最大堆保存这k个数,每次只和堆顶比,如果比堆顶小,删除堆顶,新数入堆。

参考代码

法1:运行时间:29ms  占用内存: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

法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

猜你喜欢

转载自www.cnblogs.com/carry6/p/11518544.html