leetcode——Search for a Range 排序数组中寻找目标下标范围(AC)
2014-06-19 14:58
621 查看
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
For example,
Given
return
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
assert(A!=NULL && n!=0);
vector<int> result;
int start = 0, end = n-1, mid;
while(start <= end)
{
mid = (start+end)/2;
if(A[mid] == target)
{
while(mid>=0 && A[mid]==target)
mid--;
result.push_back(++mid);
while(mid<=n-1 && A[mid]==target)
mid++;
result.push_back(--mid);
return result;
}
else if(A[mid] < target)
start = mid+1;
else
end = mid-1;
}
result.push_back(-1);
result.push_back(-1);
return result;
}
};
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].
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
assert(A!=NULL && n!=0);
vector<int> result;
int start = 0, end = n-1, mid;
while(start <= end)
{
mid = (start+end)/2;
if(A[mid] == target)
{
while(mid>=0 && A[mid]==target)
mid--;
result.push_back(++mid);
while(mid<=n-1 && A[mid]==target)
mid++;
result.push_back(--mid);
return result;
}
else if(A[mid] < target)
start = mid+1;
else
end = mid-1;
}
result.push_back(-1);
result.push_back(-1);
return result;
}
};
相关文章推荐
- leetcode题解:Search for a Range (已排序数组范围查找)
- [LeetCode-34] Search for a Range (寻找有序数组中关键值的索引范围)
- [LeetCode]—Search for a Range 有序数组查找target的下标范围
- LeetCode 34 Search for a Range (有序数组中查找给定数字的起止下标)
- [Leetcode] search for a range 寻找范围
- LeetCode 34. Search for a Range(有序数组,查找给定值范围)
- 34 Search for a Range(目标数的范围Medium)
- Search for a range寻找上下界-Leetcode
- LeetCode Search for a Range搜索特定数值的范围 三种方法求解
- leetCode 34.Search for a Range (搜索范围) 解题思路和方法
- leetcode 34. Search for a Range(C语言,查询范围)46
- 二分法——【Search Insert Position】【Search for a Range】【数字在排序数组中出现的次数】
- Leetcode刷题记——34. Search for a Range(查找一个范围)
- 二分查找有序数组中某个数的所在范围 Search for a Range
- LeetCode 34. Search for a Range(搜索范围)
- LeetCode-Search for a Range-搜索范围-二分查找
- leetcode:Search for a Range(数组,二分查找)
- 【LeetCode-面试算法经典-Java实现】【034-Search for a Range(搜索一个范围)】
- leetCode 34.Search for a Range (搜索范围) 解题思路和方法
- [LeetCode] 34. Search for a Range 搜索一个范围(Find First and Last Position of Element in Sorted Array)