难度:简单
一、题目描述:
二、解题分析:
class Solution:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
"""快排partition划分"""
if len(arr) < k or k <= 0: return []
low, high = 0, len(arr)-1
idx = self.partition(arr, low, high)
while idx != k-1:
if idx < k-1:
low = idx + 1
idx = self.partition(arr, low, high)
if k-1 < idx:
high = idx - 1
idx = self.partition(arr, low, high)
return arr[:k]
def partition(self, nums, low, high):
pivot = nums[low]
while low < high:
while low < high and pivot <= nums[high]:
high -= 1
nums[low] = nums[high]
while low < high and nums[low] <= pivot:
low += 1
nums[high] = nums[low]
nums[low] = pivot
return low
# arr.sort()
# return arr[:k]
class Solution:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
arr.sort()
return arr[:k]