658.find-k-closest-elements.go 689 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. func findClosestElements(arr []int, k int, x int) (res []int) {
  2. n := len(arr)
  3. beg, end := 0, n-1
  4. for beg <= end {
  5. mid := beg + (end-beg)/2
  6. if arr[mid] < x {
  7. beg = mid + 1
  8. } else {
  9. end = mid - 1
  10. }
  11. }
  12. if beg == n {
  13. return arr[n-k:]
  14. } else if arr[beg] == x {
  15. res = append(res, x)
  16. beg, end = beg-1, beg+1
  17. k--
  18. } else {
  19. beg, end = beg-1, beg
  20. }
  21. for ; 0 < k; k-- {
  22. if beg < 0 {
  23. res = append(res, arr[end])
  24. end++
  25. } else if n <= end {
  26. res = append(res, arr[beg])
  27. beg--
  28. } else {
  29. if x-arr[beg] <= arr[end]-x {
  30. res = append(res, arr[beg])
  31. beg--
  32. } else {
  33. res = append(res, arr[end])
  34. end++
  35. }
  36. }
  37. }
  38. sort.Ints(res)
  39. return res
  40. }