Skip to content

Latest commit

 

History

History
40 lines (34 loc) · 664 Bytes

面试题40. 最小的k个数.md

File metadata and controls

40 lines (34 loc) · 664 Bytes
//------ 思想: 快排 ----------
func QuickSort(nums []int, low, high int)  {
   if low >= high {
      return
   }

   pivot := nums[low]
   i, j := low, high
   for i < j {
      for (i<j && nums[j] >= pivot) {
         j--
      }
      nums[i] = nums[j]
      for (i< j && nums[i] <= pivot) {
         i++
      }
      nums[j] = nums[i]
   }
   nums[i] = pivot

   QuickSort(nums, low, i-1)
   QuickSort(nums, i+1, high)
}

func getLeastNumbers(nums []int, k int) []int {
   length := len(nums)
   if length > 10000 {
      return nil
   }

   if  k < 0 || k > length {
      return nil
   }
   QuickSort(nums, 0, length-1)
   return nums[:k]
}