原文来源:https://juejin.im/post/5dff2791f265da33cf1add57
题目:
输入n个整数,找出其中最小的K个数。
示例:
例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
思路:
满足海量数据找top k,由于内存大小有限,不能一次读入海量数据。
因此建立一个大小为k的容器,不断更新此容器即可。时间复杂度为o(nlogk),遍历数组,每次遍历的时候取出容器中的最大值与遍历值对比。
代码实践:
import random
class Solution:
def GetLeastNumbers(self, tinput, k):
re = []
if len(tinput) < k or k==0:
return re
for num in tinput:
if len(re) < k:
re.append(num)
elif num < max(re):
re.remove(max(re))
re.append(num)
re.sort()
return re
if __name__ == '__main__':
tinput = [random.randint(-10, 10) for i in range(10)]
print(tinput)
solution = Solution()
k = 3
array = solution.GetLeastNumbers(tinput, k)
print(array)
#输出结果:
[-8, -3, 4, 9, -2, -4, 2, 3, -9, -1]
[-9, -8, -4]