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.
思路
利用快速排序的思想进行分治。在一趟排序过程中,如果关键数(pivot)右侧有k-1个数,即说明恰好有k-1个数大于此关键数(pivot),从而找到第k大的数,递归结束;否则就对关键数两侧的部分分别进行递归即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ if (len(nums) == 1): return nums[0] else: pivot = nums[0] left = 0 right = len(nums) - 1 mid = 0 while (left < right): while (right >= 0 and left < right): if (nums[right] < pivot): nums[right], nums[mid] = nums[mid], nums[right] mid = right break right -= 1 if(left >= right): break while (left < len(nums) and left < right): if (nums[left] > pivot): nums[left], nums[mid] = nums[mid], nums[left] mid = left break left += 1 if (len(nums) - mid == k): return nums[mid] elif (len(nums) - mid > k): return self.findKthLargest(nums[mid + 1:], k) else: return self.findKthLargest(nums[:mid], k - (len(nums) - mid) )
|