Java写题解 | #最小的K个数#
最小的K个数
http://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
维护一个长度为k的最大堆,
首先填充优先队列到长度为k,此后每添加进一个元素就弹出一个元素,弹出的为队列中的最大元素,因此留下的即为最小的k个元素。
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < k; i++) {
pq.offer(input[i]);
}
for (int i = k; i < input.length; i++) {
pq.offer(input[i]);
pq.poll();
}
ArrayList<Integer> ans = new ArrayList<Integer>(pq);
return ans;
}
}
查看20道真题和解析
