方法1:排序后,取前k个数
class Solution:
def smallestK(self, arr: List[int], k: int) -> List[int]:
arr.sort()
return arr[:k]
方法2:分治
自己写快速排序算法,然后取前k个数
class Solution:
def smallestK(self, arr, k) :
# 分治
def quick_sort(arr,left ,right ):
n = len(arr)
if n == 1:
return arr
if left < right:
index = self.partition(arr, left, right)
quick_sort(arr,left,index - 1)
quick_sort(arr,index + 1,right)
if not arr or k > len(arr):
return []
if k == len(arr):
return arr
quick_sort(arr,0,len(arr) - 1)
return arr[:k]
def partition(self, nums, l, r):
import random
random_index = random.randint(l, r)
nums[l], nums[random_index] = nums[random_index], nums[l]
pivot = nums[l]
left, right = l + 1, r
while True:
while left <= right and nums[left] < pivot:
left += 1
while left <= right and nums[right] > pivot:
right -= 1
if left > right:
break
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
nums[l], nums[right] = nums[right], nums[l]
return right