【LeetCode】二分查找
给一个升序数组,找到目标值在数组中的起始和结束位置,时间复杂度为 O(log n)。
e.g.
给定数组 [5, 7, 7, 8, 8, 10] 和目标值 8,返回 [3, 4]。若目标值不在数组中,返回 [-1, -1]。
我使用最死的二分查找,分别搜索起始和结束位置。这种思路也可以使用递归实现。
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result = {-, -};
int low = , high = nums.size() - ;
while (low <= high) {
// 二分查找使用 mid = (high + low) / 2 可能溢出
int mid = low + ((high - low) >> 1);
if (nums[mid] == target) {
if (result[] == -) {
if (mid == || nums[mid] != nums[mid - ]) {
result[] = mid;
low = , high = nums.size() - ;
}
else
high = mid - ;
} else {
if (mid == nums.size() - || nums[mid] != nums[mid + ]) {
result[] = mid;
break;
}
else
low = mid + ;
}
}
else if (nums[mid] > target)
high = mid - ;
else if (nums[mid] < target)
low = mid + ;
}
return result;
}
C++ STL中自带一些使用二分查找实现的算法,
#include <algorithm>
pair<forward_iterator,forward_iterator> equal_range( forward_iterator first, forward_iterator last, const TYPE& val );
pair<forward_iterator,forward_iterator> equal_range( forward_iterator first, forward_iterator last, const TYPE& val, CompFn comp );
函数 equal_range 返回非递减序列 [first, last) 区间中等于 val 的元素区间,返回值是一对迭代器 i 和 j 。i 是 val 可插入的第一个位置(即lower_bound),j 是 val 可插入的最后一个位置(即upper_bound),equal_range 可以被认为是 lower_bound 和 upper_bound 的结合。
(lower_bound 在 [first, last) 区间进行二分查找,返回大于等于 val 的第一个元素位置。如果所有元素都小于 val,则返回 last 的位置。
upper_bound 在 [first, last) 区间进行二分查找,返回大于 val 的第一个元素位置)
因此以下代码可直接得出结果。
vector<int> searchRange(vector<int>& nums, int target) {
auto bounds = equal_range(nums.begin(), nums.end(), target);
if (bounds.first == bounds.second)
return {-, -};
return {bounds.first - nums.begin(), bounds.second - nums.begin() - };
}
vector<int> searchRange(vector<int>& nums, int target) {
int lo = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
if (lo == nums.size() || nums[lo] != target)
return {-, -};
int hi = upper_bound(nums.begin(), nums.end(), target) - nums.begin() - ;
return {lo, hi};
}
【LeetCode】二分查找的更多相关文章
- leetcode二分查找问题整理
自从做完leetcode上的三道关于二分查找的题后,我觉得它是比链表找环还恶心的题,首先能写出bugfree代码的人就不多,而且可以有各种变形,适合面试的时候不断挑战面试者,一个程序猿写代码解决问题的 ...
- leetcode 二分查找
https://oj.leetcode.com/problems/search-for-a-range/就是一个二分查找,没事练练手 public class Solution { public in ...
- [leetcode]二分查找总结
Search for a Range 1.最简单的想法,用最普通的二分查找,找到target,然后向左右扩张,大量的重复的target,就会出现O(n)效率. class Solution { pub ...
- leetcode 二分查找 Search in Rotated Sorted ArrayII
Search in Rotated Sorted Array II Total Accepted: 18500 Total Submissions: 59945My Submissions Follo ...
- Leetcode 二分查找 Search Insert Position
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie Search Insert Position Total Accepted: 14279 T ...
- leetcode 二分查找 Search in Rotated Sorted Array
Search in Rotated Sorted Array Total Accepted: 28132 Total Submissions: 98526My Submissions Suppose ...
- LeetCode 二分查找模板 II
模板 #2: int binarySearch(vector<int>& nums, int target){ if(nums.size() == 0) return -1; in ...
- LeetCode 二分查找模板 I
模板 #1: int binarySearch(vector<int>& nums, int target){ if(nums.size() == 0) return -1; in ...
- LeetCode 二分查找模板 III
模板 #3: int binarySearch(vector<int>& nums, int target){ if (nums.size() == 0) return -1; i ...
- leetcode二分查找相关
目录 33/81搜索旋转排序数组 34在排序数组中查找元素的第一个和最后一个位置 35搜索插入位置 74搜索二维矩阵 300最长上升子序列,354俄罗斯套娃信封问题 33/81搜索旋转排序数组 假设按 ...
随机推荐
- 【转载】vim 中如何替换选中行或指定几行内的文本
https://segmentfault.com/q/1010000002552573/a-1020000002552589 :'<,'>s/替换项/替换为/g 以下命令将文中所有的字符串 ...
- matplotlib python
#导入包 import matplotlib.pyplot as plt import numpy as np # 从[-1,1]中等距去50个数作为x的取值 x = np.linspace(-1, ...
- 3、My Scripts
.用for循环批量修改文件扩展名(P240) .使用专业改名命令rename来实现 .通过脚本实现sshd.rsyslog.crond.network.sysstat服务在开机时自动启动(P244) ...
- HDU 5242 Game(贪心)
http://acm.hdu.edu.cn/showproblem.php?pid=5242 题意: 给出一棵树,每个节点都有一个权值,每次可以获得从根结点(1)到叶子节点上的所有权值和,每个节点只能 ...
- HDU 4301 Divide Chocolate(DP)
http://acm.hdu.edu.cn/showproblem.php?pid=4301 题意: 有一块n*2大小的巧克力,现在某人要将这巧克力分成k个部分,每个部分大小随意,问有多少种分法. 思 ...
- 使用R语言的RTCGA包获取TCGA数据--转载
转载生信技能树 https://mp.weixin.qq.com/s/JB_329LCWqo5dY6MLawfEA TCGA数据源 - R包RTCGA的简单介绍 - 首先安装及加载包 - 指定任意基因 ...
- _itemmod_add
命令._add items XXX 为目标添加一组物品 `comment` 备注 `categoryId` 组ID `entry` 物品entry `count`数量
- 使用外网访问阿里云服务器ZooKeeper
参考网址: zookeeper单机/集群安装详解 使用外网访问阿里云服务器ZooKeeper 阿里云服务管理控制台 1. 阿里云ECS安装zookeeper 环境:我安装的是zookeeper3.4. ...
- Eclipse中出现无法找到Maven包Active Maven Profiles (comma separated)
Eclipse中出现无法找到Maven包 2014年02月25日 16:51:30 阅读数:13057 症状:出现org.maven.ide.eclipse.MAVEN2_CLASSPATH_ ...
- vscode 常用扩展推荐
1.扩展推荐 Beautify Beautify code in place for VS Code CSS Formatter Formatter for CSS ESLint ...