您的位置:首页 > 其它

数组:最小的K个数

2020-04-05 18:25 537 查看

题目描述

输入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

 

转载于:https://www.cnblogs.com/carry6/p/11518544.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
diexi0099 发布了0 篇原创文章 · 获赞 0 · 访问量 289 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: