排序思想比较简单,时间复杂度是O(nlogn),代码不展示了。
利用类似快排的思想,可以使时间复杂度为O(n)。
python
class Solution: def partition(self, arr, left, right): i = left - 1 pviot = arr[right] for j in range(left, right): if arr[j] < pviot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i+1], arr[right] = arr[right], arr[i+1] return i+1 def select(self, arr, left, right, k): i = self.partition(arr, left, right) num = i - left + 1 if num < k: self.select(arr, i+1, right, k-num) elif num > k: self.select(arr, left, i-1, k) def GetLeastNumbers_Solution(self, tinput, k): # write code here if k == 0: return [] self.select(tinput, 0, len(tinput)-1, k) return tinput[:k]