File tree Expand file tree Collapse file tree 1 file changed +41
-1
lines changed
solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array Expand file tree Collapse file tree 1 file changed +41
-1
lines changed Original file line number Diff line number Diff line change @@ -5,4 +5,44 @@ func searchRange(nums []int, target int) []int {
5
5
return []int {- 1 , - 1 }
6
6
}
7
7
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
+ }
You can’t perform that action at this time.
0 commit comments