本文實例講述了Python實現(xiàn)查找最小的k個數(shù)。分享給大家供大家參考,具體如下:
題目描述
輸入n個整數(shù),找出其中最小的K個數(shù)。例如輸入4,5,1,6,2,7,3,8這8個數(shù)字,則最小的4個數(shù)字是1,2,3,4,。
解法1
使用partition函數(shù)可以知道,使用==O(N)==的時間復雜度就可以找出第K大的數(shù)字,并且左邊的數(shù)字比這個數(shù)小,右邊的數(shù)字比這個數(shù)字大。因此可以取k為4,然后輸出前k個數(shù)字,如果需要排序的話再對結果進行排序
# -*- coding:utf-8 -*- class Solution: def PartitionOfK(self, numbers, start, end, k): if k < 0 or numbers == [] or start < 0 or end >= len(numbers) or k > end: return low, high = start, end key = numbers[low] while low < high: while low < high and numbers[high] >= key: high -= 1 numbers[low] = numbers[high] while low < high and numbers[low] <= key: low += 1 numbers[high] = numbers[low] numbers[low] = key if low < k: self.PartitionOfK(numbers, start + 1, end, k) elif low > k: self.PartitionOfK(numbers, start, end - 1, k) def GetLeastNumbers_Solution(self, tinput, k): # write code here if k <= 0 or tinput == [] or k > len(tinput): return [] self.PartitionOfK(tinput, 0, len(tinput) - 1, k) return sorted(tinput[0:k]) #測試: sol = Solution() listNum = [4,5,1,6,2,7,3,8] rel = sol.GetLeastNumbers_Solution(listNum, 4) print(rel)