forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchRange.java
More file actions
71 lines (61 loc) · 1.9 KB
/
SearchRange.java
File metadata and controls
71 lines (61 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package Algorithms.binarySearch;
public class SearchRange {
public static void main(String[] strs) {
int[] A = {1};
System.out.println(searchRange(A, 0)[0] + " " + searchRange(A, 0)[1]);
}
public static int[] searchRange(int[] A, int target) {
int[] ret = {-1, -1};
if (A == null || A.length == 0) {
return ret;
}
int len = A.length;
int left = 0;
int right = len - 1;
// so when loop end, there will be 2 elements in the array.
// search the left bound.
while (left < right - 1) {
int mid = left + (right - left) / 2;
if (target == A[mid]) {
// 如果相等,继续往左寻找边界
right = mid;
} else if (target > A[mid]) {
// move right;
left = mid;
} else {
right = mid;
}
}
if (A[left] == target) {
ret[0] = left;
} else if (A[right] == target) {
ret[0] = right;
} else {
return ret;
}
left = 0;
right = len - 1;
// so when loop end, there will be 2 elements in the array.
// search the right bound.
while (left < right - 1) {
int mid = left + (right - left) / 2;
if (target == A[mid]) {
// 如果相等,继续往右寻找右边界
left = mid;
} else if (target > A[mid]) {
// move right;
left = mid;
} else {
right = mid;
}
}
if (A[right] == target) {
ret[1] = right;
} else if (A[left] == target) {
ret[1] = left;
} else {
return ret;
}
return ret;
}
}