剑指offer-29-最小k个数
最小的K个数
http://www.nowcoder.com/questionTerminal/6a296eb82cf844ca8539b57c23e6e9bf
思路
堆维护一个有序序列(优先级队列),size()=k
注意处理k==0或者k<input.length
代码
import java.util.*; public class Solution { public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) { if(input.length<k || k==0){return new ArrayList<Integer>();} PriorityQueue<Integer> heap=new PriorityQueue<>((o1,o2)->Integer.compare(o2,o1)); for(int i=0;i<input.length;i++){ if(heap.size()<k){ heap.add(input[i]); }else{ if(heap.peek()>input[i]){ heap.poll(); heap.add(input[i]); } } } return new ArrayList<Integer>(heap); } }
剑指offer与数据结构 文章被收录于专栏
本专栏包括剑指offer题目和一些刷题用的数据结构,单调栈,树状数组,差分数组,后面还会更新红黑树等较为复杂的数据结构