无序列表list中的最大k个元素,k_from_list

方法1:内置sorted函数,然后切片:

def fun1(list1, k):
if len(list1) < k:
print(‘k too long’, list1)
pass
else:
ret = sorted(list1)[:-k - 1:-1]
print(‘fun1:’, ret)
return ret

方法2,最大堆 ,维护一个k长的列表,将列表内的最大元素和剩下的其他元素比较,大

的加进堆并弹出堆内最小元素,时间复杂度 N*logk

def fun2(list1, k):
if len(list1) < k:
print(‘k too long’, list1)
pass
else:
list_k = list1[0:k]
# print(‘list_k_origin:’, list_k)
list_orther = list1[k + 1:]
# print(list_orther)
for x in list_orther:
if x > max(list_k):
list_k.append(x)
list_k.remove(min(list_k))
print(‘fun2:’, list_k)
return list_k

方法3,快速排序,只要排到第k长度就可以停止,所以复杂度接近于O(n)

def fun3(list1, k):
if len(list1) < k:
print(‘k too long’, list1)
pass
pivot = list1[-1]
list_right = [pivot] + [x for x in list1[:-1] if x >= pivot]
len_right = len(list_right)
if len_right == k:
return list_right
elif len_right > k:
return fun3(list_right, k)
else:
list_left = [y for y in list1[:-1] if y < pivot]
return fun3(list_left, k - len_right) + list_right

import time

start1 = time.perf_counter()
list1 = [i for i in range(51)]
fun1(list1, 10)
end1 = time.perf_counter()
print(end1 - start1)

start2 = time.perf_counter()
list1 = [i for i in range(51)]
fun2(list1, 10)
end2 = time.perf_counter()
print(end2 - start2)

start3 = time.perf_counter()

list1 = [11, 8, 4, 1, 5, 2, 7, 9]

list1 = [i for i in range(51)]
print(‘fun3:’, fun3(list1, 10))
end2 = time.perf_counter()
print(end2 - start2)

结果1

fun1: [50, 49, 48, 47, 46, 45, 44, 43, 42, 41]

3.7100000000005184e-05

fun2: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]

4.5699999999995744e-05

fun3: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]

0.00010589999999999905

结果2:

fun1: [50, 49, 48, 47, 46, 45, 44, 43, 42, 41]

3.300000000000178e-05

fun2: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]

0.0001138000000000007

fun3: [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]

0.00030980000000000243

综合比较,方法三复杂度最低,时间最短,且稳定, 方法2 不稳定,但有可能比方法3时间短

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值