描述
在数组中找到第 k 大的元素。
思路
快排
代码
class Solution:
"""
@param n: An integer
@param nums: An array
@return: the Kth largest element
"""
def kthLargestElement(self, n, nums):
# write your code here
return self.quickSort(nums,0,len(nums)-1,n)
def quickSort(self,nums,left,right,n):
i = left
j = right
tmp = nums[i]
while i<j:
while i<j and tmp>=nums[j]:
j -= 1
if i<j:
nums[i] = nums[j]
i += 1
while i<j and tmp<=nums[i]:
i += 1
if i<j:
nums[j] = nums[i]
j -= 1
if i == n-1:
return tmp
elif i<n-1:
return self.quickSort(nums,i+1,right,n)
else:
return self.quickSort(nums,left,i-1,n)