Skip to content

Commit c18b31f

Browse files
author
zhaoyinglong
committed
feat: 034 golang算法提交
1 parent 733ec5c commit c18b31f

File tree

1 file changed

+41
-1
lines changed
  • solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array

1 file changed

+41
-1
lines changed

solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.go

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,44 @@ func searchRange(nums []int, target int) []int {
55
return []int{-1, -1}
66
}
77
return []int{l, r - 1}
8-
}
8+
}
9+
10+
func searchRange(nums []int, target int) []int {
11+
if len(nums) == 0 {
12+
return []int{-1, -1}
13+
}
14+
left := searchLeftIndex(nums, target)
15+
if left == nums[len(nums)-1] || nums[left] != target {
16+
return []int{-1, -1}
17+
}
18+
right := searchLeftIndex(nums, target)
19+
return []int{left, right}
20+
}
21+
22+
func searchLeftIndex(nums []int, target int) int {
23+
l, r := 0, len(nums)
24+
25+
for l < r {
26+
mid := l + (r-l)/2
27+
if nums[l] < target {
28+
l = mid + 1
29+
} else {
30+
r = mid
31+
}
32+
}
33+
return l
34+
}
35+
36+
func searchRightIndex(nums []int, target int) int {
37+
l, r := 0, len(nums)
38+
39+
for l < r {
40+
mid := l + (r-l)/2
41+
if nums[l] <= target {
42+
l = mid + 1
43+
} else {
44+
r = mid
45+
}
46+
}
47+
return l
48+
}

0 commit comments

Comments
 (0)