在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
说明:
你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
class Solution(object):
def quick_sort(self, array, l, r):
if l < r:
q = self.partition(array, l, r)
self.quick_sort(array, l, q - 1)
self.quick_sort(array, q + 1, r)
def partition(self, array, l, r):
x = array[r]
i = l - 1
for j in range(l, r):
if array[j] <= x:
i += 1
array[i], array[j] = array[j], array[i]
array[i + 1], array[r] = array[r], array[i+1]
return i + 1
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums or k > len(nums):
return nums
self.quick_sort(nums, 0, len(nums)-1)
return nums[-k]
优化版本:
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums or k > len(nums):
return nums
l = 0
r = len(nums) - 1
while True:
index = self.partition(nums, l, r)
print(nums)
if index == k - 1:
return nums[index]
elif index > k - 1:
r = index - 1
else:
l = index + 1
def partition(self, nums, left, right):
pivot = nums[left]
l = left
r = right
while l <= r:
while l <= r and nums[l] >= pivot:
l += 1
while l <= r and nums[r] < pivot:
r -= 1
print(nums[l], nums[r])
if l <= r and nums[l] < pivot and nums[r] >= pivot:
nums[l], nums[r] = nums[r], nums[l]
l += 1
r -= 1
nums[left], nums[r] = nums[r], nums[left]
return