81.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func search(nums []int, target int) bool {
  6. beg, end := 0, len(nums)-1
  7. // for empty array
  8. if end == -1 {
  9. return false
  10. }
  11. // check if the target is at the beg or at the end of the arr
  12. if nums[beg] == target || nums[end] == target {
  13. return true
  14. }
  15. // the array is not rotated
  16. if nums[beg] < nums[end] {
  17. return binarySearch(nums, target, beg, end)
  18. }
  19. // else find the top of the clip
  20. for beg < end {
  21. mid := (beg + end) / 2
  22. if nums[mid] > nums[beg] {
  23. beg = mid
  24. } else if nums[mid] < nums[end] {
  25. end = mid
  26. } else {
  27. // find the top point one by one
  28. if nums[beg] > nums[beg+1] {
  29. break
  30. }
  31. beg++
  32. }
  33. }
  34. // check the area where the target is in
  35. if target > nums[0] {
  36. return binarySearch(nums, target, 0, beg)
  37. }
  38. return binarySearch(nums, target, beg+1, len(nums)-1)
  39. }
  40. func binarySearch(nums []int, target, beg, end int) bool {
  41. for beg <= end {
  42. mid := (beg + end) / 2
  43. if nums[mid] > target {
  44. end = mid - 1
  45. } else if nums[mid] < target {
  46. beg = mid + 1
  47. } else {
  48. return true
  49. }
  50. }
  51. return false
  52. }
  53. func testSearch(nums []int, target int) {
  54. isIn := search(nums, target)
  55. checkAgain := false
  56. for _, num := range nums {
  57. if num == target {
  58. checkAgain = true
  59. break
  60. }
  61. }
  62. fmt.Println(isIn, checkAgain)
  63. }
  64. /* func main() {
  65. nums1 := []int{4, 5, 6, 7, 0, 1, 2}
  66. nums2 := []int{2, 5, 6, 0, 0, 1, 2}
  67. nums3 := []int{1, 2, 3, 4, 5}
  68. nums4 := []int{1, 1}
  69. testSearch(nums1, 1)
  70. testSearch(nums2, 0)
  71. testSearch(nums3, 5)
  72. testSearch(nums4, 0)
  73. } */