Post

LC 215 - Kth Largest Element in an Array

LC 215 - Kth Largest Element in an Array

Question

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

Example 1:

1
2
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5

Example 2:

1
2
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4

Constraints:

  • 1 <= k <= nums.length <= 105
  • -104 <= nums[i] <= 104

Question here and solution here

Solution

concept

use max heap

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        max_heap = []
        for n in nums:
            heapq.heappush(max_heap, -1*n)
        
        while k > 0:
            ans = heapq.heappop(max_heap)
            k -= 1

        return -1*ans
        
class NeetSolution:
    def findKthLargest(self, nums, k):
        return heapq.nlargest(k, nums)[-1]

Complexity

time: $O(\log n)$
space: $O(n)$

This post is licensed under CC BY 4.0 by the author.