1.题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
2.解题思路
方法一:快速排序,O(n),修改原数组
要注意和原始快排的区别, 当不满足start < end时,需要返回end,而不是直接返回
方法二:堆排序(k个元素的最大堆),O(nlogk),适合海量数据,如果待插入的值比当前已有的最大值小,则用这个数替换当前已有的最大值,如果待插入的值比当前已有的最大值大,那么这个数不可能是最小的整数之一
3.代码实现
方法一:
# -*- coding:utf-8 -*-
class Solution:
def partition(self, start, end, nums):
if start < end:
i = start
j = end + 1
K = nums[start]
while i < j:
i += 1
while i < end and nums[i] < K:
i += 1
j -= 1
while j > start and nums[j] > K:
j -= 1
if i < j:
nums[i], nums[j] = nums[j], nums[i]
nums[start], nums[j] = nums[j], nums[start]
return j
# 注意和原始快排的区别
else:
return end
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
if k == 0 or len(tinput) == 0:
return []
if k > len(tinput):
return []
start=0
end=len(tinput)-1
index = self.partition(start, end, tinput)
while True:
if index == k - 1:
print tinput[:k]
res=tinput[:k]
res.sort()
return res
elif index < k - 1:
start = index + 1
index=self.partition(start, end, tinput)
else:
end = index - 1
index=self.partition(start, end, tinput)
方法二:
import heapq
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
if k == 0 or len(tinput) == 0:
return []
if k > len(tinput):
return []
heap=[-tinput[i] for i in range(k)]
heapq.heapify(heap)
for i in range(k,len(tinput)):
if tinput[i]<-heap[0]:
heapq.heapreplace(heap,-tinput[i])
heap = [-heap[i] for i in range(k)]
heap.sort()
return heap