Problem 2 Kth Largest Element in an Array
Method 1: MaxHeap
public int findKthLargest(int[] nums, int k) {
// assume nums not null and empty
PriortyQueue<Integer> maxHeap = new PriortyQueue<>(Collections.reverseOrder());
for (int i = 0; i < nums.length; i++) {
maxHeap.offer(nums[i]);
}
int count = k;
while (count > 1) {
maxHeap.poll();
count--;
}
return maxHeap.peek();
}Method 2: MinHeap
PreviousProblem 1 K smallest In Unsorted ArrayNextProblem 3 K Cloest Value to Target in Unsorted Array
Last updated