File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int [] searchRange (int [] nums , int target ) {
3
+
4
+
5
+ int [] ans = {-1 , -1 };
6
+ // check for first occurrence if target first
7
+ ans [0 ] = search (nums , target , true );
8
+ if (ans [0 ] != -1 ) {
9
+ ans [1 ] = search (nums , target , false );
10
+ }
11
+ return ans ;
12
+ }
13
+
14
+ // this function just returns the index value of target
15
+ int search (int [] nums , int target , boolean findStartIndex ) {
16
+ int ans = -1 ;
17
+ int start = 0 ;
18
+ int end = nums .length - 1 ;
19
+ while (start <= end ) {
20
+ // find the middle element
21
+ // int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java
22
+ int mid = start + (end - start ) / 2 ;
23
+
24
+ if (target < nums [mid ]) {
25
+ end = mid - 1 ;
26
+ } else if (target > nums [mid ]) {
27
+ start = mid + 1 ;
28
+ } else {
29
+ // potential ans found
30
+ ans = mid ;
31
+ if (findStartIndex ) {
32
+ end = mid - 1 ;
33
+ } else {
34
+ start = mid + 1 ;
35
+ }
36
+ }
37
+ }
38
+ return ans ;
39
+ }
40
+ }
41
+
42
+
You can’t perform that action at this time.
0 commit comments