Your algorithm's runtime complexity must be in the order of O(log n).
2024-08-31 18:39:10
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]
.
#include<iostream>
#include<vector>
using namespace std; vector<int> searchRange(int A[], int n, int target) {
int first = 0;
int last = n - 1;
vector<int>result(2, -1);
while (first<=last)
{
int mid = (first + last) / 2;
if (A[mid] == target)
{
result[0] = mid;
result[1] = mid;
while (result[0]-1 >= first&&A[result[0]-1] == target)//当一位是反复位时才对范围跟新
--result[0];
while (result[1]+1 <= last&&A[result[1]+1] == target)
++result[1];
return result;
}
else if (A[mid] < target)
first = mid + 1;
else
last = mid - 1;
}
return result;
}
- 本文已收录于下面专栏:
最新文章
- requestAnimationFrame,Web中写动画的另一种选择
- LeetCode - Triangle
- addClass的用法和is函数的用法
- 使用Animation实现摄像机动画
- 排序之希尔排序(shell sort)
- iOS开发 AFNetworking 3.0使用遇到的问题
- [Twisted] transport和protocol解耦
- 百度编辑器ueditor如何配置
- gradient杂谈
- 完整的RecylerView的使用方法和例子
- deinstall oracle 11g on linux
- javaPNS进阶-高级推送技巧
- CoreCRM 开发实录 —— 单元测试、测试驱动开发和在线服务
- Map的迭代
- Android4.3 屏蔽HOME按键返回桌面详解(源码环境下)
- Android中SQLiteOpenHelper类的onUpgrade方法浅谈
- 使用yeoman搭建脚手架并发布到npm
- View动画(补间动画)
- Struck: Structured Output Tracking with Kernels
- 从Date类型字段获得当日周几的DAYNAME函数
热门文章
- 小米开源文件管理器MiCodeFileExplorer-源码研究(9)-入口分析
- springboot整合Beetl、BeetlSql实现ajax分页
- hdu5308 I Wanna Become A 24-Point Master(构造)
- Java IO:SocketChannel和Selector在ZooKeeper中应用
- 停止使用域名 boypay.net
- 华为畅玩5 (CUN-AL00) 刷入第三方twrp Recovery 及 root
- linux host主机名配置
- 至顶网推荐-Rpm另类用法加固Linux安全
- Writing buffer overflow exploits - a tutorial for beginners
- System.out.println 的多线程并发问题