最小的k個數-Python版


題目

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM