Back to DSA
Kth Largest Element in an Array
mediumFrom an integer array, find the element that would appear at position k from the end if the array were sorted in ascending order. This is the kth largest value, counting duplicates separately.
Examples
Example 1:
Input:
nums = [7,4,6,3,9,1], k = 3Output:
6 Example 2:
Input:
nums = [5,5,5,2,2,1], k = 4Output:
2Hints
import java.util.*;
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int num : nums) {
pq.offer(num);
if (pq.size() > k) pq.poll();
}
return pq.peek();
}
}Time complexity
O(n log k)Space complexity
O(k)