Back to DSA

Kth Largest Element in an Array

medium
Acceptance: 48%
HeapSortingDivide and Conquer

From 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 = 3
Output:6
Example 2:
Input:nums = [5,5,5,2,2,1], k = 4
Output:2

Hints

00:00
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 complexityO(n log k)
Space complexityO(k)