【LeetCode】215. Kth Largest Element in an Array 数组中的第K个最大元素(Medium)(JAVA)
题目地址: https://leetcode.com/problems/kth-largest-element-in-an-array/
题目描述:
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
题目大意
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
解题方法
- Top K 的问题用最小堆来解决
- 采用 java 提供的优先队列 PriorityQueue 构造一个最小堆(默认用的就是最小堆)
- 前面 k 个元素直接加进去, k 之后的元素,如果比堆顶的元素(也就是最下的元素)还大,就把最小的元素取出,把当前元素加进去
- 最后堆顶的元素就是第 k 大的元素(因为是最小堆所以最小的元素在堆顶,最小堆排序用的是时间复杂度 O(nlogn) 算法)
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> queue = new PriorityQueue<Integer>(k);
for (int i = 0; i < nums.length; i++) {
if (i < k) {
queue.offer(nums[i]);
} else if (nums[i] > queue.peek()) {
queue.poll();
queue.offer(nums[i]);
}
}
return queue.peek();
}
}
执行耗时:4 ms,击败了60.05% 的Java用户
内存消耗:38.4 MB,击败了97.99% 的Java用户