1
+ Given a sorted array of integers , find the starting and ending position of a given target value .
2
+
3
+ Your algorithm 's runtime complexity must be in the order of O(log n).
4
+
5
+ If the target is not found in the array , return [-1 , -1 ].
6
+
7
+ For example ,
8
+ Given [5 , 7 , 7 , 8 , 8 , 10 ] and target value 8 ,
9
+ return [3 , 4 ].
10
+
11
+ public class Solution {
12
+ public int [] searchRange (int [] A , int target ) {
13
+ int low = findLow (A , target , 0 , A .length - 1 );
14
+ int high = findHigh (A , target , 0 , A .length - 1 );
15
+ int [] ret = new int [2 ];
16
+ ret [0 ] = low ;
17
+ ret [1 ] = high ;
18
+ return ret ;
19
+ }
20
+
21
+ private int findLow (int [] A , int target , int l , int r ) {
22
+ int mid = 0 ;
23
+ int ret = -1 ;
24
+ while (l <= r ) {
25
+ mid = (l + r ) / 2 ;
26
+ if (A [mid ] == target ) {
27
+ ret = mid ;
28
+ int next = findLow (A , target , l , mid - 1 );
29
+ if (next != -1 ) {
30
+ ret = next ;
31
+ }
32
+ break ;
33
+ } else if (A [mid ] < target ) {
34
+ l = mid + 1 ;
35
+ } else {
36
+ r = mid - 1 ;
37
+ }
38
+
39
+ }
40
+ return ret ;
41
+ }
42
+
43
+ private int findHigh (int [] A , int target , int l , int r ) {
44
+ int mid = 0 ;
45
+ int ret = -1 ;
46
+ while (l <= r ) {
47
+ mid = (l + r ) / 2 ;
48
+ if (A [mid ] == target ) {
49
+ ret = mid ;
50
+ int next = findHigh (A , target , mid + 1 , r );
51
+ if (next != -1 ) {
52
+ ret = next ;
53
+ }
54
+ break ;
55
+ } else if (A [mid ] < target ) {
56
+ l = mid + 1 ;
57
+ } else {
58
+ r = mid - 1 ;
59
+ }
60
+ }
61
+ return ret ;
62
+ }
63
+ }
0 commit comments