在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicintfindKthLargest(int[] nums, int k){ if (nums.length < k) { return -1; } Queue<Integer> queue = new PriorityQueue<Integer>((a, b) -> a - b); for (int i = 0; i < nums.length; i++) { int num = nums[i]; queue.offer(num); if (queue.size() > k) { queue.poll(); } } return queue.peek(); }