1.优先队列(最小堆)
public static int[] findTopK(int[] nums, int k) {PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);for (int num : nums) {if (minHeap.size() < k) {minHeap.offer(num);} else if (num > minHeap.peek()) {minHeap.poll();minHeap.offer(num);}}int[] topK = new int[k];for (int i = k - 1; i >= 0; --i) {topK[i] = minHeap.poll();}return topK;}public static void main(String[] args) {int[] nums = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};int k = 4;int[] topK = findTopK(nums, k);System.out.println("Top " + k + " elements:");for (int num : topK) {System.out.print(num + " ");}}
输出结果:
2.Java8 stream排序
Arrays.stream(nums).boxed().sorted(Comparator.reverseOrder()).limit(4).collect(Collectors.toList())