题目描述:在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array
解答:
1.直接使用sort()方法,sort()方法的时间复杂度为O(N*logN)
注:python中列表的内置函数sort()可以对列表中的元素进行排序,而全局性的sorted()函数则对所有可迭代的序列都是适用的;并且sort()函数是内置函数,会改变当前对象,而sorted()函数只会返回一个排序后的当前对象的副本,而不会改变当前对象。
sort(fun,key,reverse=False)
参数reverse是用来表明是否逆序,默认的False情况下是按照升序的规则进行排序的,当reverse=True时,便会按照降序进行排序。
原文链接:https://blog.csdn.net/qq_29883591/article/details/51615499
代码如下:
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
nums.sort()
return nums[len(nums)-k]
2.使用快速排序方法:
快排一趟可以一个数字的最终位置,具体参考https://blog.csdn.net/scp_6453/article/details/105362500
代码如下:
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
l = 0
r = len(nums) - 1
k = len(nums) - k
j = self.quick_sort(nums,l,r,k)
return j
def quick_sort(self, nums, l, r, k):
while l < r:
j = self.partition(nums, l, r)
if j == k:
break
elif j > k:
r = j-1
else:
l = j+1
return nums[k]
def partition(self, nums, l, r):
tem = nums[l]
while l<r:
while l<r and tem <= nums[r]:
r -= 1
nums[l] = nums[r]
while l<r and tem >= nums[l]:
l += 1
nums[r] = nums[l]
nums[l] = tem
return l
3.使用堆排序
堆排序每一从数据中选出一个最大的元素,直至第K个最大元素。具体参考:https://blog.csdn.net/scp_6453/article/details/105419934
代码如下:
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
i = 0
length = len(nums)
k = length - k
num = self.heap_sort(nums, k)
return num
def heap_sort(self, nums, k):
self.build_heap(nums)
for i in range(len(nums)-1, k-1, -1):
nums[0], nums[i] = nums[i], nums[0]
self.heapify(nums, 0, i)
return nums[k]
def build_heap(self, nums):
for i in range((len(nums)-1)//2, -1, -1):
self.heapify(nums, i, len(nums))
def heapify(self, nums, i, length):
left = 2*i + 1
right = 2*i +2
if left < length and nums[left] > nums[i]:
largest = left
else:
largest = i
if right < length and nums[right] > nums[largest]:
largest = right
if largest != i:
nums[i], nums[largest] = nums[largest], nums[i]
self.heapify(nums, largest, length
注:还可以使用python中堆相关的库函数
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
from heapq import heappush,heapreplace
# 使用堆的nlargest(n,iter)返回前n个最大的数,倒序排练
return nlargest(k,nums)[-1]
作者:yu-fa-tang-you-dian-tian
链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/215-shu-zu-zhong-de-di-kge-zui-da-yuan-su-python-s/
来源:力扣(LeetCode)