Problem: 215. 数组中的第K个最大元素
题目描述
思路
1.维护一个小顶堆minHeap,并将数组nums中的前k个元素添加到minHeap中;
2.从nums中k后面的元素开始,若当前nums中的元素大于小顶堆中的堆顶元素,则将其minHeap中堆顶的元素取出,将当前的nums中的元素添加到minHeap中
3.返回最终的minHeap堆顶的元素即为第K大元素;
复杂度
时间复杂度:
O ( n l o g n ) O(nlogn) O(nlogn);其中 n n n是数组的大小
空间复杂度:
O ( n ) O(n) O(n)
Code
class Solution {
/**
* Find the KTH largest element in the array
*
* @param nums Given array
* @param k Given number
* @return int
*/
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>(k, Comparator.comparingInt(a -> a));
for (int i = 0; i < k; ++i) {
minHeap.offer(nums[i]);
}
// Starting from k, compare nums[i] with the first element each time
for (int i = k; i < nums.length; i++) {
Integer topElement = minHeap.peek();
// If it is larger than the top of the heap, the top of the heap element
// is removed from the queue and the top element is rejoined.
if (nums[i] > topElement) {
minHeap.poll();
minHeap.offer(nums[i]);
}
}
// Returns the smallest value in the smallest
// heap of the largest k elements of the natural order
return minHeap.peek();
}
}