标签:eve main ++ java asn ever lang out get
Java 大根堆,维护k个最小的元素,时间复杂度O(KlogK)。
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int n = sc.nextInt(), k = sc.nextInt();
PriorityQueue<Integer> q = new PriorityQueue<>(Collections.reverseOrder());
for(int i=0; i < n; i++) {
int t = sc.nextInt();
if(q.isEmpty() || q.size() < k) q.offer(t);
else {
int min = q.peek();
if(t < min) {
q.poll();
q.offer(t);
}
}
}
ArrayList<Integer> res = new ArrayList<>();
while(!q.isEmpty()) res.add(q.poll());
for(int i=k-1; i > 0; i--)
System.out.print(res.get(i) + " ");
System.out.println(res.get(0));
}
}
}
标签:eve main ++ java asn ever lang out get
原文地址:https://www.cnblogs.com/lixyuan/p/13264065.html