-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathleetcode0033.go
54 lines (44 loc) · 886 Bytes
/
leetcode0033.go
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
/*
LeetCode 33: https://leetcode.com/problems/search-in-rotated-sorted-array/
*/
package leetcode
func search(nums []int, target int) int {
if len(nums) == 0 {
return -1
}
binarySearch := func(nums []int, start, end, target int) int {
for start <= end {
mid := (start + end) / 2
if nums[mid] == target {
return mid
}
if nums[mid] < target {
start = mid + 1
} else {
end = mid - 1
}
}
return -1
}
left, right, smallest := 0, len(nums)-1, 0
for nums[left] > nums[right] {
if right == left+1 {
smallest = right
break
}
mid := (left + right) / 2
if nums[mid] > nums[left] {
left = mid
} else {
right = mid
}
}
if target >= nums[0] {
end := smallest - 1
if smallest == 0 {
end = len(nums) - 1
}
return binarySearch(nums, 0, end, target)
}
return binarySearch(nums, smallest, len(nums)-1, target)
}