1 无脑sort选第K个
a.sort(reverse=True)
a[]
2 堆,直接无脑调用nlargest(K, a)[-1]
import heapq
heapq.nlargest(K,a)[-1]
3 维护一个大小为K的最小堆
建堆:O(n)
最终为O(nlogK)
不满K个,直接进堆操作
满了K个,如果当前元素 > 堆顶元素,那就替换该元素,建堆。
- 这样保证了,最后遍历完毕后,K大小的堆的堆顶存储的就是第K大元素
import heapq
class Solution:
def findKth(self, a, n, K):
# write code here
# return heapq.nlargest(K, a)[-1]
heap = []
for i in range(n):
item = a[i]
if i < K:
heapq.heappush(heap, item)
else:
if a[i] > heap[0]:
heapq.heapreplace(heap, item)
return heap[0]
4 借鉴 快排 思路K
# -*- coding:utf-8 -*-
import heapq
class Solution:
def findKth(self, a, n, K):
# write code here
# return heapq.nlargest(K, a)[-1]
# heap = []
# for i in range(n):
# item = a[i]
# if i < K:
# heapq.heappush(heap, item)
# else:
# if a[i] > heap[0]:
# heapq.heapreplace(heap, item)
# return heap[0]
return self.qsort(a, 0, n-1, K)
def qsort(self, a, low, high, K):
p = self.partition(a, low, high)
if K == (high - p + 1):
return a[p]
elif (high - p + 1) > K:
return self.qsort(a, p+1, high, K)
else:
return self.qsort(a, low, p-1, K-( high-p + 1) )
def partition(self, a, low, high):
l, r = low, high
pivot = a[l] # 中轴值选择最左边一定要从右边r指针开始动,把l的指针指向当做一个空箱子,可以覆盖值
while l < r:
#动手,动右指针
while l < r and a[r] >= pivot:
r -= 1
a[l] = a[r] #
#动左指针
while l < r and a[l] <= pivot:
l += 1
a[r] = a[l]
a[l] = pivot
return l