1
1
package com .fishercoder .solutions ;
2
2
3
- import com .fishercoder .common .utils .CommonUtils ;
4
-
5
- /**Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
6
-
7
- Your algorithm's runtime complexity must be in the order of O(log n).
8
-
9
- If the target is not found in the array, return [-1, -1].
3
+ /**
4
+ * 34. Search for a Range
5
+ *
6
+ * Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
7
+ * Your algorithm's runtime complexity must be in the order of O(log n).
8
+ * If the target is not found in the array, return [-1, -1].
10
9
11
10
For example,
12
11
Given [5, 7, 7, 8, 8, 10] and target value 8,
13
12
return [3, 4].
13
+
14
14
*/
15
15
public class _34 {
16
16
17
- public static int [] searchRange (int [] nums , int target ) {
18
- int start = 0 ;
19
- int end = nums .length - 1 ;
17
+ public int [] searchRange (int [] nums , int target ) {
20
18
int [] range = new int [2 ];
21
19
range [0 ] = -1 ;
22
20
range [1 ] = -1 ;
21
+ if (nums == null || nums .length == 0 ) {
22
+ return range ;
23
+ }
24
+ int start = 0 ;
25
+ int end = nums .length - 1 ;
23
26
while (start + 1 < end ) {
24
27
int mid = start + (end - start ) / 2 ;
25
28
if (nums [mid ] == target ) {
@@ -40,14 +43,14 @@ public static int[] searchRange(int[] nums, int target) {
40
43
end = mid ;
41
44
}
42
45
}
46
+
43
47
if (nums [start ] == target ) {
44
48
range [0 ] = start ;
45
49
while (start + 1 < nums .length && nums [start ] == nums [start + 1 ]) {
46
50
start ++;
47
51
}
48
52
range [1 ] = start ;
49
- }
50
- if (nums [end ] == target ) {
53
+ } else if (nums [end ] == target ) {
51
54
range [1 ] = end ;
52
55
while (end - 1 >= 0 && nums [end ] == nums [end - 1 ]) {
53
56
end --;
@@ -56,11 +59,4 @@ public static int[] searchRange(int[] nums, int target) {
56
59
}
57
60
return range ;
58
61
}
59
-
60
- public static void main (String ... strings ) {
61
- int [] nums = new int []{1 , 2 , 3 };
62
- int target = 2 ;
63
- int [] result = searchRange (nums , target );
64
- CommonUtils .printArray (result );
65
- }
66
62
}
0 commit comments