-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathleetcode0034.go
40 lines (34 loc) · 864 Bytes
/
leetcode0034.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
/*
LeetCode 34: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
*/
package leetcode
func searchRange(nums []int, target int) []int {
searchFirstOrLast := func(nums []int, target int, isFirst bool) int {
left, right := 0, len(nums)-1
for left <= right {
mid := (left + right) / 2
if nums[mid] == target {
if isFirst {
if mid == 0 || nums[mid-1] != target {
return mid
}
right = mid - 1
} else {
if mid == len(nums)-1 || nums[mid+1] != target {
return mid
}
left = mid + 1
}
} else if nums[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return -1
}
result := make([]int, 0)
result = append(result, searchFirstOrLast(nums, target, true))
result = append(result, searchFirstOrLast(nums, target, false))
return result
}