Skip to main content

215. Kth Largest Element in an Array

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

Python

Sort and get

  • Time: O(N log N)
  • Space: O(1)
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort(reverse=True)
return nums[k-1]

Heap

  • Time: O(N log k)
  • Space: O(k)
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return heapq.nlargest(k, nums)[-1]