-
Notifications
You must be signed in to change notification settings - Fork 0
/
34.go
56 lines (49 loc) · 1.03 KB
/
34.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
55
56
package main
func searchRange(nums []int, target int) []int {
var startingPosition, endingPosition int
startingPosition = bs(nums, target, 0, len(nums)-1, true)
if startingPosition == -1 {
endingPosition = -1
} else {
endingPosition = bs(nums, target, startingPosition, len(nums)-1, false)
}
return []int{startingPosition, endingPosition}
}
func bs(nums []int, target, l, r int, startingPosition bool) int {
if r < l {
return -1
}
if l == r {
if nums[l] == target {
return l
} else {
return -1
}
}
m := (l + r) / 2
if nums[m] > target {
return bs(nums, target, l, m, startingPosition)
} else if nums[m] < target {
return bs(nums, target, m+1, r, startingPosition)
} else {
if startingPosition {
return min(bs(nums, target, l, m-1, startingPosition), m)
} else {
return max(bs(nums, target, m+1, r, startingPosition), m)
}
}
}
func min(x, y int) int {
if x < y && x != -1 {
return x
} else {
return y
}
}
func max(x, y int) int {
if x > y && x != -1 {
return x
} else {
return y
}
}