优先队列PriorityQueue修改Comparator为最大堆,空间O(k), 时间O(nlog(k))
import java.util.*; public class Main { public Main() { } public boolean getMinK(int n, Integer[] pInputArray, int k, Integer[] pOutputArray) { if (k > n) return false; PriorityQueue<Integer> pq = new PriorityQueue<>(k, new Comparator<Integer>(){ public int compare(Integer o1, Integer o2) { return o2 - o1; } }); for (Integer i : pInputArray) { if (pq.size() == k && i < pq.peek()) { pq.poll(); } if (pq.size() < k) { pq.offer(i); } } for (int i = k - 1; i >= 0; i--) { pOutputArray[i] = pq.poll(); } return true; } public static void main(String[] args) { Main solution = new Main(); Scanner in = new Scanner(System.in); while (in.hasNextInt()) { int n = in.nextInt(), k = in.nextInt(); Integer[] pInputArray = new Integer[n]; Integer[] pOutputArray = new Integer[k]; for (int i = 0; i < n; i++) { pInputArray[i] = in.nextInt(); } boolean res = solution.getMinK(n, pInputArray, k, pOutputArray); if (res) { for (Integer i : pOutputArray) { System.out.print(i + " "); } System.out.println(); } } } }