题解 | #最小的K个数#(大根堆、优先级对列、比较器)

最小的K个数

http://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf

import java.util.*;

public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
        ArrayList<Integer> res=new ArrayList<>();
        if(k==0||k>input.length) return res;
        PriorityQueue<Integer> maxHeap=new PriorityQueue<>(k,new Comparator<Integer>(){
            @Override
            public int compare(Integer o1,Integer o2){
                //比较时返回正数,这个数会被挪到后面,这相当于是从大到小排
                return o2-o1;
            }
        });
        for(int i=0;i<input.length;i++){
            if(maxHeap.size()!=k){
                maxHeap.offer(input[i]);
            }else if(input[i]<maxHeap.peek()){
                maxHeap.poll();
                maxHeap.offer(input[i]);
            }
        }
        for(int num:maxHeap){
            res.add(num);
        }
        return res; 
        
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务