解法
- 首先容易想到的做 次冒泡, 复杂度为
- 或者先排序再找第 个元素,复杂度为
- 建立 个元素的大根堆,遍历后续 个元素,如果比根小就替换根, 复杂度
- 利用分割技术 (partitioning),复杂度为
迭代形式
import random
def kthSmallest(data, k):
"Find the nth rank ordered element (the least value has rank 0)."
data = list(data)
if not 0 <= k < len(data):
raise ValueError('not enough elements for the given rank')
while True:
pivot = random.choice(data)
pcount = 0
low, high = [], []
for elem in data:
if elem < pivot:
low.append(elem)
elif elem > pivot:
high.append(elem)
else:
pcount += 1
if k < len(low):
data = low
elif k < len(low) + pcount:
return pivot
else:
data = high
k -= len(low) + pcount
递归形式
def kthSmallest(data, k):
if not 0 <= k < len(data):
raise ValueError('not enough elements for the given rank')
pivot = random.choice(data)
pcount = 0
low, high = [], []
for elem in data:
if elem < pivot:
low.append(elem)
elif elem > pivot:
high.append(elem)
else:
pcount += 1
if k < len(low):
return kthSmallest(low, k)
elif k < len(low) + pcount:
return pivot
else:
return kthSmallest(high, k-len(low)-pcount)
测试
A = [i for i in range(1000)]
random.shuffle(A)
for i in range(len(A)):
assert(kthSmallest(A, i) == i)
复杂度分析
来源:CSDN
作者:颹蕭蕭
链接:https://blog.csdn.net/itnerd/article/details/103946663