A MEDIUM problem, but easier than the recent easy level problems I chose.
DESCRIPTION:
Given an array of integers 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]
For example,Given [5, 7, 7, 8, 8, 10]
and target value 8,return [3, 4]
ANALYSIS:
To avoid thinking about the detail problems existing in "if(nums[i]==nums[i-1])", like nums[0] and nums[length-1], I use 'start' and 'end', and initialize them as '-1' and '-1'. We can judge if the target has occurred by judging if 'start==-1', and to determine the value of 'end', we can use 'end++'.
SOLUTION:
public static int[] searchRange(int[] nums, int target) {
int start=-1;
int end=-1;
for(int i=0;i<nums.length;i++){
if(nums[i]==target&&start==-1){
start=i;end=i;
}else if(nums[i]==target&&start!=-1){
end++;
}
}
int []r={start,end};
return r;
}