題目
輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4,。
思路
partition
代碼
# -*- coding:utf-8 -*-
class Solution:
def partition(self, tinput, left, right):
leftIndex = left
tmp = tinput[left]
while left <= right:
while left <= right and tinput[left] <= tmp: left += 1
while left <= right and tinput[right] > tmp: right -= 1
if left <= right: tinput[left], tinput[right] = tinput[right], tinput[left]
tinput[leftIndex], tinput[right] = tinput[right], tinput[leftIndex]
return right
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
if k == 0 or not tinput or k > len(tinput): return []
part = self.partition(tinput, 0, len(tinput) - 1)
left = 0; right = len(tinput) - 1
while part != k - 1:
if part < k - 1:
left = part + 1
else:
right = part - 1
part = self.partition(tinput, left, right)
return sorted(tinput[:k])