Java优先队列
static Comparator<Integer> cmp = new Comparator<Integer>(){
public int compare(Integer e1,Integer e2){
return e1 - e2;//默认升序排列,大根堆
}
};
Queue<Integer> q = new PriorityQueue(cmp);
static Comparator<Integer> cmp = new Comparator<Integer>(){
public int compare(Integer e1,Integer e2){
return e2 - e1;
}
};
public int[] getLeastNumbers(int[] arr, int k) {
if(arr.length ==0 || k == 0) return new int[0];
int []res = new int[k];
Queue<Integer> q = new PriorityQueue(cmp);
for(int i = 0;i < k;i++){
q.offer(arr[i]);
}
for(int i = k;i < arr.length;i++){
if(arr[i] < q.peek()){
q.poll();
q.offer(arr[i]);
}
}
int idx = 0;
while(!q.isEmpty()) res[idx++] = q.poll();
return res;
}
``
网友评论