215. Kth Largest Element in an Array
Given an integer array nums and an integer k, return thek<sup>th</sup>largest element in the array.
Note that it is the k<sup>th</sup> largest element in the sorted order, not the k<sup>th</sup> distinct element.
Can you solve it without sorting?
Example 1:
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Example 2:
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
Constraints:
1 <= k <= nums.length <= 10<sup>5</sup>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup>
Solution:
# Quick Select
# Time complexity: O(n) in average, O(n^2) in worst case
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
k = len(nums) - k
left, right = 0, len(nums) - 1
while left < right:
pivot = self.partition(nums, left, right)
if pivot < k:
left = pivot + 1
elif pivot > k:
right = pivot - 1
else:
break
return nums[k]
def partition(self, nums: List[int], left: int, right: int) -> int:
pivot, fill = nums[right], left
for i in range(left, right):
if nums[i] <= pivot:
nums[fill], nums[i] = nums[i], nums[fill]
fill += 1
nums[fill], nums[right] = nums[right], nums[fill]
return fill