您的位置:首页 > 其它

Search for a Range

2015-07-24 10:19 176 查看
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]
.

Analyse: Binary search.

Runtime: 12ms.

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result;
if(nums.size() == 0) return result;

int left = findLeft(nums, target);
int right = findRight(nums, target);

result.push_back(left);
result.push_back(right);

return result;
}

int findLeft(vector<int> &nums, int target){
int low = 0, high = nums.size() - 1;

while(low <= high){
int mid = (low + high) / 2;
if(nums[mid] < target) low = mid + 1;
else high = mid - 1;
}
if(nums[low] != target) return -1;
else return low;
}

int findRight(vector<int> &nums, int target){
int low = 0, high = nums.size() - 1;

while(low <= high){
int mid = (low + high) / 2;
if(nums[mid] > target) high = mid - 1;
else low = mid + 1;
}
if(nums[high] != target) return -1;
else return high;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: