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]
這道題參考了博文http://blog.csdn.net/linhuanmars/article/details/20593391
這篇文章講得很好,尤其是左右下標滑動找到結果的方式,很棒!
class Solution {
public int[] searchRange(int[] nums, int target) {
int ll = 0;
int lr = nums.length - 1;
int rl = 0;
int rr = nums.length - 1;
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
int m1 = 0;
int m2= 0;
if(nums == null || nums.length == 0){
return result;
}
while(ll <= lr){
m1 = (ll + lr)/2;
if(nums[m1] < target){
ll = m1 + 1;
}else{
lr = m1 -1;
}
}
while(rl <= rr){
m2 = (rl + rr)/2;
if(nums[m2] <= target){
rl = m2 +1;
}else{
rr = m2 -1;
}
}
if(ll <= rr){
result[0] = ll;
result[1] = rr;
}
return result;
}
}