最小的k個數
輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4,。
# -*- coding:utf-8 -*-
import random
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
# python就是方便,此處注意k大於數組長度的情況要返回空數組:
return sorted(tinput)[:k] if k<=len(tinput) and tinput else []
# 其他方法:
# 快速排序:
def quick_sort(arr):
if not arr:
return []
pivot = arr[0]
left = quick_sort([x for x in arr[1: ] if x < pivot])
right = quick_sort([x for x in arr[1: ] if x >= pivot])
return left + [pivot] + right
if not tinput or k > len(tinput):
return []
tinput = quick_sort(tinput)
return tinput[: k]
# 冒泡排序:
def bubble_sort(lst):
if lst == []:
return []
for i in range(len(lst)):
for j in range(1, len(lst) - i):
if lst[j-1] > lst[j]:
lst[j-1], lst[j] = lst[j], lst[j-1]
return lst
if tinput == [] or k > len(tinput):
return []
tinput = bubble_sort(tinput)
return tinput[: k]
# Partiton思想:不只用在快速排序中,還可以用於 Selection algorithm(在無序數組中尋找第K大的值)中
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