Post

Kth Largest Element in an Array

LeetCode https://leetcode.cn/problems/kth-largest-element-in-an-array/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    public int findKthLargest(int[] nums, int k) {
        Queue<Integer> maxHeap = new PriorityQueue<>(
            (e1, e2) -> e2 - e1
        );

        for (int num : nums) {
            maxHeap.add(num);
        }
        
        for (int i = 0; i < k-1; i++) {
            maxHeap.poll();
        }

        return maxHeap.poll();
    }
}

Complexity

  • Time = O(nlogn)
  • Space = O(n)
This post is licensed under CC BY 4.0 by the author.