1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| func getLeastNumbers(arr []int, k int) []int { if k == 0 || len(arr) == 0 { return []int{0} }
return quickSort(arr, 0, len(arr)-1, k-1) }
func quickSort(nums []int, left, right, index int) []int { mid := partition(nums, left, right) if mid == index { return nums[:mid+1] } else if mid > index { return quickSort(nums, left, mid-1, index) } else { return quickSort(nums, mid+1, right, index) }
return nil }
func partition(nums []int, left, right int) int { pivot := nums[left] for left < right { for left < right && nums[right] >= pivot { right-- } nums[left] = nums[right]
for left < right && nums[left] <= pivot { left++ }
nums[right] = nums[left] } nums[left] = pivot
return left }
|