-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution034.java
45 lines (40 loc) · 1.12 KB
/
Solution034.java
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
package algorithm.leetcode;
import java.util.Map;
/**
* @author: mayuan
* @desc:
* @date: 2018/08/20
*/
public class Solution034 {
public static void main(String[] args) {
int[] nums = {5, 7, 7, 8, 8, 10};
Solution034 test = new Solution034();
int[] ans = test.searchRange(nums, 8);
for (int n : ans) {
System.out.println(n);
}
}
public int[] searchRange(int[] nums, int target) {
int first = binarySearch(nums, target);
int last = binarySearch(nums, target + 1) - 1;
if (first == nums.length || nums[first] != target) {
return new int[]{-1, -1};
} else {
return new int[]{first, Math.max(first, last)};
}
}
private int binarySearch(int[] nums, int target) {
int left = 0;
// 注意此处的取值
int right = nums.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}