题目内容
https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
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.
题目思路
我想到的是冒泡排序,先确定K的大小和总体长度关系来确定是选择求最大K个元素还是最小l-k个元素。不过可以通过这道题目来复习一下手写排序算法。
程序代码
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
l=len(nums)
if not nums or l<k:
return False
self.quik_sort(nums,0,l-1)
return nums[-k]
def quik_sort(self,L,left,right):
if left <= right:
key = L[left]
i = left
j = right
while i < j:
while i < j and key <= L[j]:
j -= 1
L[i] = L[j]
while i < j and L[i] <= key:
i += 1
L[j] = L[i]
L[i] = key
self.quik_sort(L, left, i - 1)
self.quik_sort(L, i + 1, right)