leetcode题解:Search for a Range (已排序数组范围查找)
2024-08-29 17:06:08
- 题目:
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]
.
- 说明:
1)已排序数组查找,二分查找
- 实现:
- STL实现
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
auto low_bound=lower_bound(A,A+n,target);//第一个大于等于>=target元素的指针位置
auto up_bound=upper_bound(low_bound,A+n,target);//第一个大于>target元素的指针位置
if(*low_bound==target)//target是否存在于A[]
{
return vector<int>{distance(A,low_bound),distance(A,prev(up_bound))};
}
else return vector<int>{-,-}; }
};
2. 常规实现
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
int low=,high=n-,middle;
bool isFind=false;
vector<int> vec;
while(low<=high)//二分查找,直至找到,并置标志true
{
middle=(low+high)/;
if(A[middle]==target)
{
isFind=true;
break;
}
else if(A[middle]<target)
low=middle+;
else
high=middle-;
}
if(isFind)//如果找到,确定开始、结束与target相等的元素位置
{
low=middle;
high=middle;
while(low>=&&A[low]==target) low--;//下界要>=0
low++;
while(high<=n-&&A[high]==target) high++;//上界要<=n-1
high--;
vec.push_back(low);
vec.push_back(high);
}
else//没有目标值
{
vec.push_back(-);
vec.push_back(-);
}
return vec;
}
};
最新文章
- iPhone4下window各个部分的高度
- Javascript学习笔记:对象的属性类型
- 对线程调度中Thread.sleep(0)的深入理解
- Android 播放视频文件
- iText导出pdf、word、图片
- Leetcode#89 Gray Code
- 如何用HTML5+PhoneGap写个Path项目
- log4j级别输出
- [置顶] 使用struts拦截器+注解实现网络安全要求中的日志审计功能
- ZOJ 1171 Sorting the Photos
- sass学习笔记 -- sass的四种编译方法
- 14. leetcode 383. Ransom Note
- Ocelot中文文档-日志
- 判断浏览器的名称,区分360的ie和谷歌内核
- 福州大学软件工程1816 | W班 第6次作业WordCount成绩排名
- nodejs的某些api~(六)HTTPS
- 利用svg描边+css3实现边框逐渐消失小动画
- Oracle启动关闭
- 常量&;字符编码
- 网页使用思源字体 CSS