4. 代码实现:
- /**
- * @Author Ragty
- * @Description 有界堆排序
- * @Date 19:49 2019/6/12
- **/
- public List<T> topK(int k,List<T> list,Comparator<T> comparator) {
- PriorityQueue<T> heap = new PriorityQueue<T>(list.size(),comparator);
- for (T element : list) {
- if (heap.size() <k) {
- heap.offer(element);
- continue;
- }
- int cmp = comparator.compare(element,heap.peek());
- if (cmp>0) {
- heap.poll();
- heap.offer(element);
- }
- }
- List<T> res = new LinkedList<T>();
- while (!heap.isEmpty()) {
- res.add(heap.poll(http://www.my516.com));
- }
- return res;
- }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
测试代码:
来源: http://www.bubuko.com/infodetail-3107660.html