Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created June 2, 2015 20:23
Show Gist options
  • Save cangoal/6e3545f8f96122685ed4 to your computer and use it in GitHub Desktop.
Save cangoal/6e3545f8f96122685ed4 to your computer and use it in GitHub Desktop.
LeetCode - Search for a Range
// Solution 1: 3 binary searches
public int[] searchRange(int[] nums, int target) {
int[] ret = new int[]{-1, -1};
if(nums == null || nums.length == 0) return ret;
int left = 0, right = nums.length - 1;
int mid = (left + right) / 2;
while(left < right){
if(nums[mid] == target){
ret[0] = mid;
ret[1] = mid;
break;
}else if(nums[mid] < target){
left = mid + 1;
}else{
right = mid - 1;
}
mid = (left + right) / 2;
}
if(nums[mid] != target) return ret;
int ll = left, lr = mid - 1;
int rl = mid + 1, rr = right;
while(ll <= lr){
int m = (ll + lr) / 2;
if(nums[m] == target){
lr = m - 1;
} else {
ll = m + 1;
}
}
ret[0] = ll;
while(rl <= rr){
int m = (rl + rr) / 2;
if(nums[m] == target){
rl = m + 1;
} else {
rr = m - 1;
}
}
ret[1] = rr;
return ret;
}
// Solution 2: 2 binary searches
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)/2;
if(A[m]<target)
{
ll = m+1;
}
else
{
lr = m-1;
}
}
int rl = 0;
int rr = A.length-1;
while(rl<=rr)
{
int m = (rl+rr)/2;
if(A[m]<=target)
{
rl = m+1;
}
else
{
rr = m-1;
}
}
if(ll<=rr)
{
res[0] = ll;
res[1] = rr;
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment