给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。
请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
这题我用了快速排序的方法做的
不过耗时还是有些长
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
length = len(nums)
k -= 1
def quick_sort(nums,left,right):
bound = nums[left]
i,j = left,right
while(i<j):
while(i<j and nums[j]<=bound):
j -= 1
nums[i] = nums[j]
while(i<j and nums[i]>=bound):
i += 1
nums[j] = nums[i]
nums[i] = bound
return i
index = quick_sort(nums,0,length-1)
while(index != k):
if index > k:
index = quick_sort(nums,0,index-1)
elif index < k:
index = quick_sort(nums,index+1,length-1)
return nums[k]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-elements