Given a sorted array of integers, 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
return
Given
[5, 7, 7, 8, 8, 10] and target value 8,return
[3, 4].
public class Solution {
private int[] searchRangeAux(int[] nums, int target, int l, int r){
int[] ret = new int[2];
if(r - l == 1){
if(target == nums[l]){
ret[0] = l;
ret[1] = r-1;
}
else{
ret[0] = -1;
ret[1] = -1;
}
return ret;
}else if(r - l < 1){
ret[0] = -1;
ret[1] = -1;
return ret;
}
int m = (l + r) / 2;
if(nums[m] == target){
int[] leftR = searchRangeAux(nums, target, l, m);
int[] rightR = searchRangeAux(nums, target, m, r);
// Error: forgot to valid the return ...
if(-1 == leftR[0]){
ret[0] = rightR[0];
}
else{
ret[0] = leftR[0];
}
if(-1 == rightR[1]){
ret[1] = leftR[1];
}
else{
ret[1] = rightR[1];
}
return ret;
}
else if(nums[m] > target){
return searchRangeAux(nums, target, l, m);
}
else{
return searchRangeAux(nums, target, m, r);
}
}
public int[] searchRange(int[] nums, int target) {
int len = nums.length;
return searchRangeAux(nums, target, 0, len);
}
}
No comments:
Post a Comment