import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param input int整型一维数组
* @param k int整型
* @return int整型ArrayList
*/
public ArrayList<Integer> GetLeastNumbers_Solution (int[] input, int k) {
// write code here
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int x : input){
pq.offer(x);
}
ArrayList<Integer> ans = new ArrayList<>();
while(!pq.isEmpty()){
if(k <= 0)break;
ans.add(pq.poll());
k--;
}
return ans;
}
}
使用优先队列,不需要排序

京公网安备 11010502036488号