Given an array of integers nums 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].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

这道题让我们在一个有序整数数组中寻找相同目标值的起始和结束位置,而且限定了时间复杂度为 O(logn),这是典型的二分查找法的时间复杂度,所以这里也需要用此方法,思路是首先对原数组使用二分查找法,找出其中一个目标值的位置,然后向两边搜索找出起始和结束的位置,代码如下:

解法一:

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int idx = search(nums, , nums.size() - , target);
if (idx == -) return {-, -};
int left = idx, right = idx;
while (left > && nums[left - ] == nums[idx]) --left;
while (right < nums.size() - && nums[right + ] == nums[idx]) ++right;
return {left, right};
}
int search(vector<int>& nums, int left, int right, int target) {
if (left > right) return -;
int mid = left + (right - left) / ;
if (nums[mid] == target) return mid;
if (nums[mid] < target) return search(nums, mid + , right, target);
else return search(nums, left, mid - , target);
}
};

可能有些人会觉得上面的算法不是严格意义上的 O(logn) 的算法,因为在最坏的情况下会变成 O(n),比如当数组里的数全是目标值的话,从中间向两边找边界就会一直遍历完整个数组,那么下面来看一种真正意义上的 O(logn) 的算法,使用两次二分查找法,第一次找到左边界,第二次调用找到右边界即可,具体代码如下:

解法二:

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res(, -);
int left = , right = nums.size();
while (left < right) {
int mid = left + (right - left) / ;
if (nums[mid] < target) left = mid + ;
else right = mid;
}
if (right == nums.size() || nums[right] != target) return res;
res[] = right;
right = nums.size();
while (left < right) {
int mid = left + (right - left) / ;
if (nums[mid] <= target) left = mid + ;
else right = mid;
}
res[] = right - ;
return res;
}
};

其实我们也可以只使用一个二分查找的子函数,来同时查找出第一个和最后一个位置。如何只用查找第一个大于等于目标值的二分函数来查找整个范围呢,这里用到了一个小 trick,首先来查找起始位置的 target,就是在数组中查找第一个大于等于 target 的位置,当返回的位置越界,或者该位置上的值不等于 target 时,表示数组中没有 target,直接返回 {-1, -1} 即可。若查找到了 target 值,则再查找第一个大于等于 target+1 的位置,然后把返回的位置减1,就是 target 的最后一个位置,即便是返回的值越界了,减1后也不会越界,这样就实现了使用一个二分查找函数来解题啦,参见代码如下:

解法三:

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int start = firstGreaterEqual(nums, target);
if (start == nums.size() || nums[start] != target) return {-, -};
return {start, firstGreaterEqual(nums, target + ) - };
}
int firstGreaterEqual(vector<int>& nums, int target) {
int left = , right = nums.size();
while (left < right) {
int mid = left + (right - left) / ;
if (nums[mid] < target) left = mid + ;
else right = mid;
}
return right;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/34

类似题目:

First Bad Version

参考资料:

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/discuss/14699/Clean-iterative-solution-with-two-binary-searches-(with-explanation)

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/discuss/14701/A-very-simple-Java-solution-with-only-one-binary-search-algorithm

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Search for a Range 搜索一个范围的更多相关文章

  1. [LeetCode] 34. Search for a Range 搜索一个范围(Find First and Last Position of Element in Sorted Array)

    原题目:Search for a Range, 现在题目改为: 34. Find First and Last Position of Element in Sorted Array Given an ...

  2. [LeetCode] Search a 2D Matrix 搜索一个二维矩阵

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  3. [CareerCup] 11.6 Search a 2D Matrix 搜索一个二维矩阵

    11.6 Given an M x N matrix in which each row and each column is sorted in ascending order, write a m ...

  4. [LeetCode] 74. Search a 2D Matrix 搜索一个二维矩阵

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  5. LeetCode: Search for a Range 解题报告

    Search for a RangeGiven a sorted array of integers, find the starting and ending position of a given ...

  6. lintcode: search for a range 搜索区间

    题目 搜索区间 给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置. 如果目标值不在数组中,则返回[-1, -1] 样例 给出[5, 7, 7, 8, 8, 10]和目 ...

  7. [LeetCode] Search for a Range [34]

    题目 Given a sorted array of integers, find the starting and ending position of a given target value. ...

  8. LeetCode Search for a Range (二分查找)

    题意 Given a sorted array of integers, find the starting and ending position of a given target value. ...

  9. [Leetcode] search a 2d matrix 搜索二维矩阵

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

随机推荐

  1. 在thinkphp中,写的博文标签多对多关系的标签频率统计算法

    常常看到别人的博客里面,或者网站里面有这样随机颜色,但字体大小与标签出现频率有关的标签云,于是自己就想写一个.至于颜色的随机显示,那就很简单了,这里就不列代码. 因为正在学thinkphp,所以数据查 ...

  2. 安装完成后在命令行运行bash时报错0x80070057

    在命令运行bash 提示如下: 解决方法,不启用旧版本控制台: 右键命令提示栏 打开属性,把勾选去掉如下图红色边框标识: 然后重启,就可以使用,也包括可以打开Bash on Unbuntu on Wi ...

  3. 网络爬虫: 从allitebooks.com抓取书籍信息并从amazon.com抓取价格(1): 基础知识Beautiful Soup

    开始学习网络数据挖掘方面的知识,首先从Beautiful Soup入手(Beautiful Soup是一个Python库,功能是从HTML和XML中解析数据),打算以三篇博文纪录学习Beautiful ...

  4. Quartz.net 开源job调度框架(二)----定点执行

    在上一篇  Quartz.net 开源job调度框架(一) 中讲到了基本的使用以及配置job轮训数据执行 这种做法适用于对数据操作实时性要求不高的场景,在实际场景中还有一种比较常用的场景就是我们需要在 ...

  5. React Native图片控件的使用

    首先定义组件 import { AppRegistry, StyleSheet, Text, View, Image,} from 'react-native'; 然后将render返回中的模版增加I ...

  6. 学会给你的类(及成员)来定制一套自己的Attribute吧

    在通过Visual Studio创建的C#程序集中,都包含了一个AssemblyInfo.cs的文件,在这个文件中,我们常常会看到这样的代码 [assembly: AssemblyTitle(&quo ...

  7. java.lang.Class.isAssignableFrom()用法解析

    一.概述: 此方法主要用来判断 "参数类" 是否是 "源类" 的子类.接口实现类,或者与 "源类" 相同,在此情况下返回 true; 二.格 ...

  8. 工作中常用的git命令

    一 常用Git命令 git clone:(区分SSH or HTTP) git init:初始化仓库 二 Git命令详解 Git Bash下,cd /c git clone,从远程Git版本库克隆一份 ...

  9. 在centos 服务器上安装phalcon框架 undefined symbol: php_pdo_get_dbh_ce

    去git 下载对应版本的框架 命令行: sudo yum install php-devel pcre-devel gcc make 然后使用GIT clone到服务器上,然后 git clone g ...

  10. JavaScript中‘this’关键词的优雅解释

    本文转载自:众成翻译 译者:MinweiShen 链接:http://www.zcfy.cc/article/901 原文:https://rainsoft.io/gentle-explanation ...