数组:最小的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
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 旋转数组中的最小数字
- 九度oj 1504:把数组排成最小的数 (贪心)
- 把数组排成最小的数
- 找出数组中最大最小数(用指针)
- js获取数组中最小的值的方法 Math.min.apply(),apply(),call()方法使用
- 剑指Offer-旋转数组的最小数字
- 找出数组中的最小值--递归实现
- 寻找一维数组int num[5]中最大、最小及其坐标位置并 打印输出。(数组值从键盘读取)
- 实验8,编写一个模板函数求数组中的最大值和最小值
- 面试题33—把数组排成最小的数
- 分治法寻找数组最大的两个数和最小的两个数
- 剑指offer系列(7)——旋转数组的最小数字
- 06、旋转数组的最小数字
- 旋转数组中的最小数字
- 寻找数组中最小的K个元素
- 算法学习十五----找数组最大值和最小值
- 编程之美——寻找数组中的最大值和最小值
- JavaScript获取数组最小值和最大值的方法
- 剑指Offer——旋转数组的最小数字
- JAVA实现旋转数组的最小数字问题(《剑指offer》)