34. Find First and Last Position of Element in Sorted Array
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res={-1,-1};
if(nums.length==0)
return res;
int low=0,high=nums.length-1,mid=-1;
while(low<=high){
mid=(low+high)/2;
if(target>nums[mid]){
low=mid+1;
}else if(target<nums[mid]){
high=mid-1;
}else{
res[0]=mid;
res[1]=mid;
break;
}
}
while(res[0]>0&&nums[res[0]-1]==nums[res[0]]){
res[0]--;
}
while(res[1]>=0&&res[1]<nums.length-1&&nums[res[1]+1]==nums[res[1]]){
res[1]++;
}
return res;
}
}