博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
#34 Search for a Range
阅读量:4682 次
发布时间:2019-06-09

本文共 1019 字,大约阅读时间需要 3 分钟。

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].

 

解法:find函数,返回找到数字的迭代器,然后用distance函数返回下标值,后面就是循环找出相同的个数

class Solution {public:    vector
searchRange(vector
& nums, int target) { vector
::iterator it; vector
result; it = find(nums.begin(),nums.end(),target); if(it == nums.end()) { result.push_back(-1); result.push_back(-1); return result; } int i = distance(nums.begin(),it); int n = nums.size(); result.push_back(i); while(*it == nums[++i] && i < n); //确保++i不要数组溢出 result.push_back(i-1); return result; }};

 

转载于:https://www.cnblogs.com/xiaohaigege/p/5319341.html

你可能感兴趣的文章
[AHOI2005] SHUFFLE 洗牌
查看>>
Python3.4+Django1.9+Bootstrap3
查看>>
Delphi笔记(GL_Scene安装及简单使用)
查看>>
6-MySQL-Ubuntu-操作数据表的基本操作(一)
查看>>
mysql linux 安装卸载
查看>>
技术工作者的四大核心价值观
查看>>
双向循环链表程序(C语言版)
查看>>
TypeScript - 类型断言
查看>>
Java VisualVM 插件地址
查看>>
python文件处理
查看>>
Git 命令
查看>>
VMware workstaion上传虚拟机到VMware EXSI 5.5
查看>>
[转载] 高等应用数学问题的matlab求解——第1章 计算机数学语言概述
查看>>
jmeter插件管理——Plugins Manager的使用
查看>>
python中Error loading package list:pypi.python.org解决方法
查看>>
CCPC2019吉林省赛&&东北地区赛游记
查看>>
bzoj1303: [CQOI2009]中位数图
查看>>
VS2010 SP1安装卡在VS10Sp1-KB983509处的解决
查看>>
HDU 4006: The kth great number
查看>>
将PDF格式转换成其它文档
查看>>