老大让我输出我们的服务中,使用GPU最多的top10,我一想,这就是最经典的topk问题,我想使用堆解决。工程实践中,直接实现一个堆结构是低效率的事情,而Java实际上提供了这样的容器类,记录简单使用如下,可以获取输入数据的topk
public class MainTest {
public static void main(String[] args) {
Integer[] arr = {3,2,5,8,71,3,69,5,4,9,82,5,55,96,485,357};
System.out.println(top(Arrays.asList(arr),5));
}
public static <T extends Comparable<T>> List<T> top(List<T> list,int top){
if (list == null){
throw new RuntimeException("list is null!");
}
PriorityQueue<T> queue = new PriorityQueue<>(top);
list.forEach(t -> {
if (queue.size() < top){
queue.add(t);
}else if (queue.peek().compareTo(t) < 0){
queue.poll();
queue.add(t);
}
});
LinkedList<T> arr = new LinkedList<>();
while (!queue.isEmpty()){
arr.addFirst(queue.poll());
}
return arr;
}
}