题目描述:
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,
思路1:
用堆排序
代码1.1:
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
import heapq
if tinput == None or len(tinput) < k or len(tinput) <= 0 or k <= 0:
return []
return heapq.nsmallest(k, tinput)
代码1.2(不调用包):
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
# 用大根堆
if len(tinput) < k:
return []
for i in range(1, k):
tinput = self.build_heap(tinput, i)
for j in range(len(tinput)):
if tinput[j] < tinput[0]:
tinput = self.heapify(tinput, j, k)
return sorted(tinput[:k])
def build_heap(self, l, i):
cur = i
while cur > 0:
father = (cur - 1) // 2
if l[cur] > l[father]:
l[cur], l[father] = l[father], l[cur]
cur = father
else:
break
return l
def heapify(self, l, j, k):
l[0], l[j] = l[j], l[0]
cur = 0
left = 1
while left < k:
right = left + 1
if right < k:
if l[left] > l[right]:
max_lr = left
else:
max_lr = right
else:
max_lr = left
if l[cur] < l[max_lr]:
l[cur], l[max_lr] = l[max_lr], l[cur]
cur = max_lr
left = cur * 2 + 1
else:
break
return l
思路2:
用快排的思想做