最小的k个数(important!)

题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

python solution:

# -*- coding:utf-8 -*-
import random
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        n = len(tinput)
        if n<=0 or k>n:
            return []
        if k==0:
            return []
        start = 0
        end = n-1
        index = self.partition(tinput,start,end)
        while index != k-1:
            if index >k-1:
                end = index - 1
                index = self.partition(tinput,start,end)
            else:
                start = index +1
                index = self.partition(tinput,start,end)
        res = tinput[:k]
        res=sorted(res)
        return res
 
    def partition(self,arr,start,end):
        if start==end:
            p=start
        else:
            p = random.randrange(start,end)
        arr[p],arr[end]=arr[end],arr[p]
        small = start-1
        for i in range(start,end):
            if arr[i]<arr[end]:
                small+=1
                if small != i:
                    arr[small],arr[i]=arr[i],arr[small]
        small +=1
        arr[small],arr[end]=arr[end],arr[small]
        return small

猜你喜欢

转载自www.cnblogs.com/bernieloveslife/p/10424217.html