215. Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
Solution: Partition
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
idx = len(nums) - k
return self.find_idx(nums, idx, 0, len(nums) - 1)
def find_idx(self, nums, idx, low, high):
pivot = nums[low + (high - low) / 2]
left, right = self.partition(nums, low, high, pivot)
if left < idx < right:
return nums[idx]
if idx <= left:
return self.find_idx(nums, idx, low, left)
else:
return self.find_idx(nums, idx, right, high)
def partition(self, nums, low, high, pivot):
idx = low
while idx <= high:
if nums[idx] < pivot:
self.swap(nums, idx, low)
low += 1
idx += 1
elif nums[idx] > pivot:
self.swap(nums, idx, high)
high -= 1
else:
idx += 1
return low - 1, high + 1
def swap(self, nums, left, right):
nums[left], nums[right] = nums[right], nums[left]
Lessons:
- Time complexity:
- Average:
- Worst: .
- Quick-select