215. Kth Largest Element in an Array
LeetCode 215. Kth Largest Element in an Array
Description
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.
Example 1:
Constraints:
1 <= k <= nums.length <= 10^4
-10^4 <= nums[i] <= 10^4
Tags
Divide and Conquer, Heap
Solution
Solution 1:
We can perform the partition operation adopted in quick sort algorithm until pivot == k
.
l == r
, returnnums[l]
;pivot == k
, returnnums[k]
;pivot > k
,partition(left, pivot - 1)
;pivot < k
,partition(pivot + 1, right)
;
Solution 2:
We use heap with capacity of k
, where the root is the minimum element, to store the top-k largest elements in the given array. We keep pushing elements into the heap until the size of the heap is k
. Then, we compare the current element with the root of the heap, if the root is smaller, we pop an element from the heap and push the current one into it. Finally, we return the root.
Complexity
Solution 1:
Time complexity: , the worst case is we partition the array for
n
times. We can introduce random partition to speed up this up to ;Space complexity: , for recursion stack.
Solution 2:
Time complexity:
Space complexity:
Code
Solution 1 (Quick-sort):
Solution 2 (Heap):
Last updated
Was this helpful?