题目
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。(牛客网上要求结果有序)
解法1,使用快排思想
1 # -*- coding:utf-8 -*-
2 class Solution: 3 def GetLeastNumbers_Solution(self, tinput, k): 4 # write code here
5 smallk=[] 6 length = len(tinput) 7 if k<=0 or k>length or length==0: 8 return smallk 9 if k==length: 10 return sorted(tinput) 11 left =0 12 right=length-1
13 while left <= right: # 要<=
14 small = self.quicksort(tinput,left,right) 15 if small == k: 16 for i in range(k): 17 smallk.append(tinput[i]) 18 break
19 if small >k: 20 right = small-1
21 if small <k: 22 left = small+1
23 return sorted(smallk) 24 def quicksort(self,tinput,left,right): 25 small =left -1
26 temp = tinput[right] 27 for index in range(left,right,1): 28 if tinput[index]<temp: 29 small+=1
30 if small != index: 31 tinput[small],tinput[index] = tinput[index] ,tinput[small] 32 small +=1
33 # tinput[small],temp = temp,tinput[small]不能交换tinput[right]
34 tinput[small], tinput[right] = tinput[right], tinput[small] 35 return small
解法2,创建一个k大小的容器(略),适合海量数据