# Search for a Range

class Solution {
public:
// 记住最后递归的left 和right 能够减少寻找左边界和右边界的时间。
int binarySearch(vector<int> &nums, int left, int right, int target) {
int mid = (left + right) / 2;
if(left > right)
return -1;
if(nums[mid] == target)
return mid;
if(nums[mid] > target)
return binarySearch(nums, left, mid - 1, target);
if(nums[mid] < target)
return binarySearch(nums, mid + 1, right, target);
}
// 设置isRight bool 值来判断是左边界还是有边界。
int binarySearchLR(vector<int> &nums, int left, int right, int target, bool isRight) {
int mid = (left + right) / 2;
if(isRight) {
if(left == right)
return left;
if(nums[mid] == target && nums[mid + 1] != target)
return mid;
else if(nums[mid] == target && nums[mid + 1] == target )
return binarySearchLR(nums, mid + 1, right, target, true);
else
return binarySearchLR(nums, left, mid - 1, target, true);
}
else {
// 这里需要考虑mid - 1是否会越界，因为只有两个元素时，mid总等于left，而如果left是0，则mid - 1会越界
if(left == right || left == right - 1) {
if(nums[left] == target)
return left;
return right;
}
if(nums[mid] == target && nums[mid - 1] != target)
return mid;
else if(nums[mid] == target && nums[mid - 1] == target )
return binarySearchLR(nums, left, mid - 1, target, false);
else
return binarySearchLR(nums, mid + 1, right, target, false);
}
}
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result{-1, -1};
if(nums.empty())
return result;
int n = nums.size();
int findIndex = binarySearch(nums, 0, n - 1, target);
if(findIndex == -1)
return result;
result[0] = binarySearchLR(nums, 0, findIndex, target, false);
result[1] = binarySearchLR(nums, findIndex, n - 1, target, true);
return result;
}
};
• 本文已收录于以下专栏：

## A Route Search Method for Electric Vehicles in Consideration of Range

• 2013年02月28日 14:51
• 443KB
• 下载

## 【LeetCode-面试算法经典-Java实现】【034-Search for a Range（搜索一个范围）】

【034-Search for a Range（搜索一个范围）】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题　　Given a sorted array of intege...

## LeetCode: Search for a Range 解题报告

Search for a Range Given a sorted array of integers, find the starting and ending position of a g...

## leetcode:34. Search for a Range

Given an array of integers sorted in ascending order, find the starting and ending position of a giv...
• Earl211
• 2017年03月15日 13:54
• 198

## [Leetcode]Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value. ...

## [C++]LeetCode: 65 Search for a Range

举报原因： 您举报文章：Search for a Range 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)