您的位置:首页 > 其它

[Leetcode] 34. Search for a Range

2015-03-15 00:01 459 查看
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
[5, 7, 7, 8, 8, 10]
and target value 8,

return
[3, 4]
.
值得注意的是,加上 ll <= rr的判断语句,是为了判断是否真的找到了target number,如果找到了,ll必然小于等于rr。
public class Solution {
public int[] searchRange(int[] A, int target) {
int[] result = {-1, -1};
if(A == null || A.length == 0) return result;
int ll = 0;
int lr = A.length - 1;
while(ll <= lr){
int mid = (ll + lr) / 2;
if(A[mid] < target){
ll = mid + 1;
} else {
lr = mid - 1;
}
}
int rl = 0;
int rr = A.length - 1;
while(rl <= rr){
int mid = (rl + rr) / 2;
if(A[mid] <= target){
rl = mid + 1;
} else {
rr = mid - 1;
}
}
if(ll <= rr){
result[0] = ll;
result[1] = rr;
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: