leetcode 陣列中的第K個最大元素

2021-09-25 20:56:15 字數 860 閱讀 1322

1.簡單粗暴 排序選擇第i-k-1元素

2.對計數陣列進行遍歷後(執行c[i] += c[i-1]),c[i]代表待排序陣列中值小於等於i的元素個數,而c[i-1]代表值小於等於i-1的元素個數,如果 c[i-1] < k並且k <= c[i],那麼待排序陣列中第k小的數必定就是值為i的數!查詢就可以結束了。所以只需要找到第乙個滿足條件k <= c[i]的i即可。

class solution:

def findkthlargest(self, nums: list[int], k: int) -> int:

pivot = num[low]

while (low < high):

while (low < high and num[high] > pivot):

high -= 1

while (low < high and num[low] < pivot):

low += 1

num[low],num[high] = num[high],num[low]

num[high] = pivot

return high,num

def findkth(num,low,high,k): #找到陣列裡第k個數

index=(partition(num,low,high))[0]

print((partition(num,low,high))[1])

if index==k:return num[index]

if indexreturn findkth(num,index+1,high,k)

else:

return findkth(num,low,index-1,k)

LeetCode 215 陣列中的第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 說明 你可以假設 k 總是有效的,且 1...

LeetCode 215 陣列中的第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 說明 你可以假設 k 總是有效的,且 1...

Leetcode215 陣列中的第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 說明 你可以假設 k 總是有效的,且 1...