題目
輸入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大小的容器(略),適合海量數據