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

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

题目

Given an array of integers sorted in ascending order, 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].

分析

给出了一个int类型的升序的数组,查找数组中等于给出的数字的起始坐标和最终坐标。如果找不到和给出的数相等的数,就返回[-1, -1]。

因为数组已经排好序了,因此我们无须对该数组进行排序。

最简单的做法就是按顺序遍历整个数组,知道找到目标数,但是这个算法的时间复杂度为O(n),明显大于题目所要求的O(log n)。

所以我们采用二分查找的算法求解改题目,而二分查找的时间复杂度为O(log n),符合要求。

class Solution {public:    vector
searchRange(vector
& nums, int target) { // 若数组为空,则不存在符合要求的数 if (nums.size() == 0) { return {-1, -1}; } int a = 0, b = nums.size() - 1; int index = (b + a) / 2; while (b >= a) { if (nums[index] == target) { int i, j; for (i = index; nums[i] == target && i < nums.size(); i++); for (j = index; nums[j] == target && j >= 0; j--); return {j+1, i-1}; } else if (nums[index] >target) { b = index - 1; index = (b + a) / 2; } else { a = index + 1; index = (b + a) / 2; } } return {-1, -1}; }};
在找到符合要求的数之后,还要查找该数前面和后面的数,看是否符合。

转载地址:http://tibmb.baihongyu.com/

你可能感兴趣的文章
从端到云——工业物联网项目全栈快速开发
查看>>
LoRa vs NB-IOT:哪个物联网标准更具优势?
查看>>
移动周刊第 205 期:Google 正式发布 ARCore 预览版、iOS 工程打包速度提升十倍的解决方案...
查看>>
八大 IoT 安全关键技术解析
查看>>
有钱 Python,没钱 PHP,编程语言也嫌贫爱富
查看>>
Docker是啥?容器变革的火花?
查看>>
假如从餐饮店的角度来看架构…
查看>>
这个充电宝太黑科技了,又小又不用自己带线,长见识了~
查看>>
HDC.2019后再发力,AppGallery Connect服务新升级
查看>>
网易云音乐热评的规律,44万条数据告诉你
查看>>
超神!GitHub 标星 5.5w,如何用 Python 实现所有算法?
查看>>
扛住100亿次请求——如何做一个“有把握”的春晚红包系统
查看>>
在北京看场雪为什么这么难?
查看>>
新年了,5G手机芯片,到底买谁?
查看>>
疫情之下「在家办公模式」开启,你该选择哪些远程协同工具?
查看>>
如何使用pdpipe与Pandas构建管道?
查看>>
远程办公的33种预测
查看>>
阿里巴巴架构师:十问业务中台和我的答案
查看>>
华为云发布三类六款计算实例 打造更强云端计算能力
查看>>
PHP 语言地位遭受挑战,PHP 程序员路在何方?
查看>>