main_optimize.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. )
  9. func main() {
  10. input := bufio.NewScanner(os.Stdin)
  11. var output int
  12. var digits []int
  13. var target int
  14. for input.Scan() {
  15. line := input.Text()
  16. digits = []int{}
  17. values := strings.Split(line, " ")
  18. length := len(values)
  19. for index, v := range values {
  20. d, _ := strconv.Atoi(v)
  21. if index == length-1 {
  22. target = d
  23. break
  24. }
  25. digits = append(digits, d)
  26. }
  27. fmt.Println("start ---", digits, target)
  28. output = search(digits, target)
  29. fmt.Println(output)
  30. }
  31. }
  32. func search(nums []int, target int) int {
  33. if len(nums) == 0 {
  34. return 0
  35. }
  36. var leftIdx = binarySearchLeft(nums, target)
  37. var rightIdx = binarySearchLeft(nums, target+1)
  38. if nums[leftIdx] != target {
  39. return 0
  40. }
  41. if leftIdx == rightIdx {
  42. return 1
  43. }
  44. if nums[rightIdx] == target {
  45. rightIdx += 1
  46. }
  47. return rightIdx - leftIdx
  48. }
  49. // left最后都会和right相等,nums[right]永远大于等于target。
  50. // 就会使得nums[left]永远小于等于target.for结束的时候left和right相等,
  51. // 所以只需要判断nums[left] ?= target, 就能判断nums中是否存在target
  52. func binarySearchLeft(nums []int, target int) int {
  53. var left, right = 0, len(nums) - 1
  54. var mid int
  55. for left < right {
  56. mid = (left + right) / 2
  57. if nums[mid] >= target {
  58. right = mid
  59. } else {
  60. left = mid + 1
  61. }
  62. }
  63. return left
  64. }