Kth Largest Element in an Array
// solution1 : MaxHeap
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<Integer>((a, b) -> (a - b));
for (int num : nums) {
heap.add(num);
if (heap.size() > k) heap.poll();
}
return heap.poll();
}
}
// Time Complexity : O(nlogk); // add an element in a heap of size k is O(logk);
// Space Complexity : O(k);
// solution2:MinHeap
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<Integer>((a, b) -> (b - a));
for (int num : nums) {
heap.add(num);
}
for (int i = 0; i < k - 1; i++) {
heap.poll();
}
return heap.poll();
}
}
最后更新于
这有帮助吗?