-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path34.在排序数组中查找元素的第一个和最后一个位置.java
67 lines (58 loc) · 1.76 KB
/
34.在排序数组中查找元素的第一个和最后一个位置.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import sun.awt.image.ImageAccessException;
/*
* @lc app=leetcode.cn id=34 lang=java
*
* [34] 在排序数组中查找元素的第一个和最后一个位置
*/
// @lc code=start
class Solution {
public int[] searchRange(int[] nums, int target) {
/*int index;
int[] res = new int[] {-1,-1};
if(nums.length == 0 || nums == null || nums[0] > target || nums[nums.length - 1] < target){
return res;
}
for(index = 0; index < nums.length; index++){
if(nums[index] == target){
res[0] = index;
break;
}else{
continue;
}
}
for(index = nums.length - 1; index >= 0; index--){
if(nums[index] == target){
res[1] = index;
break;
}else{
continue;
}
}
return res;
*/
int[] res = {-1,-1};
int leftIndex = extremeIndertioonIndex(nums, target, true);
if(leftIndex == nums.length || nums[leftIndex] != target){
return res;
}
res[0] = leftIndex;
res[1] = extremeIndertioonIndex(nums, target, false) - 1;
return res;
}
//boolean: left(这个参数表示:如果为true,则递归搜索左区间,否则递归搜索右区间)
private int extremeIndertioonIndex(int[] nums, int target, boolean left){
int low = 0;
int high = nums.length;
while(low < high){
int mid = (low + high) / 2;
if(nums[mid] > target || (left && target == nums[mid])){
high = mid;
}
else{
low = mid + 1;
}
}
return low;
}
}
// @lc code=end