参考了code ganker大牛,http://blog.csdn.net/linhuanmars/article/details/20593391
二分法边界条件老是想不明白, 不知道等号到底归在哪边。这题也想了好久。既然要找边界,左边就是不停往左,右边就是不停往后。所以找左边边界的时候,A[m]=target的情况是放在左边继续递归的。然后右边找边界的时候,A[m]=target的情况诗放在右边继续递归的。
下面是Leetcode AC代码
public int[] searchRange(int[] A, int target) {
int[] res = {-1,-1};
if(A==null||A.length==0){
return res;
}
int ll = 0;
int lr = A.length-1;
while(ll<=lr){
int m = ll+(lr-ll)/2;
if(A[m] >= target){
lr=m-1;
}else{
ll=m+1;
}
}
int rl=0;
int rr=A.length-1;
while(rl<=rr){
int m = rl+(rr-rl)/2;
if(A[m] <= target){
rl=m+1;
}
else{
rr=m-1;
}
}
if(ll<=rr){
res[0] = ll;
res[1] = rr;
}
return res;
}