Thursday, February 4, 2016

LeetCode Q34: Search for a Range

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].

Straight forward solution. Binary search first followed by a local scanning around mid pointer.

class Solution {
public:
int rBound(vector<int>& nums, int target, int l, int r){
if(l>r)
return -1;
while(l<=r){
int mid = (l+r)/2;
if(target<nums[mid]){
r=mid-1;
continue;
}
if(target>nums[mid]){
l=mid+1;
continue;
}
if(target==nums[mid]){
if((mid+1<nums.size() && nums[mid]!=nums[mid+1]) || (mid==nums.size()-1))
return mid;
else
l=mid+1;
}
}
return -1;
}
int lBound(vector<int>& nums, int target, int l, int r){
if(l>r)
return -1;
while(l<=r){
int mid = (l+r)/2;
if(target<nums[mid]){
r=mid-1;
continue;
}
if(target>nums[mid]){
l=mid+1;
continue;
}
if(target==nums[mid]){
if((mid-1>=0 && nums[mid]!=nums[mid-1]) || (mid==0))
return mid;
else
r=mid-1;
}
}
return -1;
}
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res;
if(nums.empty())
return res;
int lb = lBound(nums, target, 0, nums.size()-1);
int rb = rBound(nums, target, 0, nums.size()-1);
res.push_back(lb);
res.push_back(rb);
return res;
}
};

No comments:

Post a Comment