在未排序的數(shù)組中找到第 k 個(gè)最大的元素。請(qǐng)注意,你需要找的是數(shù)組排序后的第 k 個(gè)最大的元素,而不是第 k 個(gè)不同的元素。
示例 1:
輸入: [3,2,1,5,6,4] 和 k = 2
輸出: 5
示例 2:
輸入: [3,2,3,1,2,4,5,5,6] 和 k = 4
輸出: 4
說(shuō)明:
你可以假設(shè) k 總是有效的,且 1 ≤ k ≤ 數(shù)組的長(zhǎng)度。
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
class Solution:
def partition(self, nums, low, high):
pivot = nums[low]
j = low
for i in range(low+1, high+1):
if (nums[i] > pivot):
nums[i],nums[j+1] = nums[j+1],nums[i]
j += 1
nums[low],nums[j] = nums[j],nums[low]
return j
def findKthLargest(self, nums: List[int], k: int) -> int:
low = 0
high = len(nums) -1
while(low <= high): #邊界條件的確定
index = self.partition(nums, low, high) #self 的用法
print(index,nums[index])
if(index == k-1):
return nums[index]
elif(index < k-1):
low = index + 1
else:
high = index - 1
```