• 题目:

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)已排序数组查找,二分查找

  • 实现:

  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;
}
};

最新文章

  1. iPhone4下window各个部分的高度
  2. Javascript学习笔记:对象的属性类型
  3. 对线程调度中Thread.sleep(0)的深入理解
  4. Android 播放视频文件
  5. iText导出pdf、word、图片
  6. Leetcode#89 Gray Code
  7. 如何用HTML5+PhoneGap写个Path项目
  8. log4j级别输出
  9. [置顶] 使用struts拦截器+注解实现网络安全要求中的日志审计功能
  10. ZOJ 1171 Sorting the Photos
  11. sass学习笔记 -- sass的四种编译方法
  12. 14. leetcode 383. Ransom Note
  13. Ocelot中文文档-日志
  14. 判断浏览器的名称,区分360的ie和谷歌内核
  15. 福州大学软件工程1816 | W班 第6次作业WordCount成绩排名
  16. nodejs的某些api~(六)HTTPS
  17. 利用svg描边+css3实现边框逐渐消失小动画
  18. Oracle启动关闭
  19. 常量&amp;字符编码
  20. 网页使用思源字体 CSS

热门文章

  1. Spring bean 创建过程源码解析
  2. yii2.0查询慢的原因
  3. server reached pm.max_children setting (5), consider raising it
  4. github 小白教程
  5. BAT脚本编写教程入门提高篇
  6. [ CodeVS冲杯之路 ] P1017
  7. EditText双光标问题
  8. Appium+python自动化21-DesiredCapabilities详解【转载】
  9. Mongodb的使用(上)
  10. (1)Java Spring