长度为n的列表,查找出前k大的元素,这种算法的时间度是少的吗

如果求前10大的元素,还有更少时间的算法吗
纯属好奇,望大侠不吝赐教

###列表
temp0 =  range(2000,5001)
temp1 =  range(200,500)
temp2 =  range(801,8000)
a = sorted(temp0)
b = sorted(temp1)
c = sorted(temp2)
d = b + c + a

### 计算过程
temp = []
t = 0
for i in d:
    t += 1
    le = len(temp)
    if le < 10:
        temp.insert(0,i)
        temp = sorted(temp)        
    else:
        f = temp[0]
        if i > f:
            temp[0] = i
            temp = sorted(temp) 
print("总数:",len(d))
print("查询次数:",t)
print(temp)
#计算结果
总数: 10500
查询次数: 10500
[7990, 7991, 7992, 7993, 7994, 7995, 7996, 7997, 7998, 7999]
阅读 3k
3 个回答
import heapq
d = list(range(200,500)) +  list(range(801,8000)) + list(range(2000,5001))
heapq.heapify(d)    # 堆树,时间复杂度O(n)
heapq.nlargest(10, d)

你的算法的插入后排序,可以用二分法插入优化

import bisect

# temp.insert(0,i)
# temp = sorted(temp) 优化为
bisect.insort(temp, i)

# temp[0] = i
# temp = sorted(temp) 优化为
temp.pop(0)
bisect.insort(temp, i)

可以试试堆排序

你这已经是线性时间复杂度了,再低的话除非是对数时间

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题