您的位置:首页 > 其它

Leetcode-Search for a range

2014-11-21 05:06 218 查看
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]
.

Have you met this question in a real interview?

Analysis:
We need to do two binary search. The first finds out the left boundary and the second finds out the right boundary.
if mid==target, we then check whether mid-1==target, if yes, we then continue to search [start,mid-1] until we find the left boundary.
Solution:

public class Solution {
public int[] searchRange(int[] A, int target) {
int[] res = new int[]{-1,-1};
if (A.length==0) return res;

int start = 0, end = A.length-1;

//Find left range.

while (start<=end){
int mid = (start+end)/2;
if (A[mid]==target){
//find right range also.
if (mid+1==A.length || A[mid+1]!=target) res[1] = mid;

//Check left
if (mid-1==-1 || A[mid-1]!=target){
res[0]=mid;
break;
} else {
end = mid-1;
continue;
}
} else if (A[mid]>target) end = mid-1;
else start = mid+1;
}

if (start>end) return res;
if (res[0]!=-1 && res[1]!=-1) return res;

//Find right
start = 0;
end = A.length-1;
while (start<=end){
int mid = (start+end)/2;
if (A[mid]==target){
//Check right
if (mid+1==A.length || A[mid+1]!=target){
res[1]=mid;
break;
} else {
start = mid+1;
continue;
}
} else if (A[mid]>target) end = mid-1;
else start = mid+1;
}

return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: