/**
* 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
* 如果数组中不存在目标值,返回 [-1, -1]。
* 链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
*/
public class SearchRange {
public static int[] searchRange(int[] nums, int target) {
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
if(nums.length == 0){
return result;
}
int low = 0;
int high = nums.length - 1;
int mid = 0;
while(low <= high){
mid = (low + high) / 2;
if(nums[mid] == target){
break;
}else if(nums[mid] < target){
low = mid + 1;
}else{
high = mid - 1;
}
}
if(nums[mid] != target){
return result;
}
int left = mid;
int right = mid;
while(left > 0){
left --;
if(nums[left] != target){
left = left + 1;
break;
}
}
while(right < high){
right++;
if(nums[right] != target){
right = right - 1;
break;
}
}
result[0] = left;
result[1] = right;
return result;
}
public static void main(String[] args){
int[] arr = {1, 2, 2, 2, 5};
int[] result = searchRange(arr, 2);
for(int i: result){
System.out.println(i);
}
}
}