[LeetCode] 704. Binary Search
Description
Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Note:
- You may assume that all elements in
numsare unique. - n will be in the range
[1, 10000]. - The value of each element in
numswill be in the range[-9999, 9999].
Analyse
从一个list里找出一个数,不存在则返回-1
使用二分查找,每次将问题的规模减半
int search(vector<int>& nums, int target)
{
int left = 0;
int right = nums.size() - 1;
int mid = (left + right) / 2;
while (left <= right)
{
if (nums[mid] == target)
{
return mid;
}
else if (nums[mid] > target)
{
right = mid - 1;
}
else if (nums[mid] < target)
{
left = mid + 1;
}
mid = (left + right) / 2;
}
return -1;
}
leetcode中最快的方法是调用STL中的lower_bound函数
template <class ForwardIterator, class T>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val);
lower_bound在[first, last)的左闭右开区间寻找第一个不小于val的元素,采用了二分查找的思想
Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.
在这个区间找到满足条件的就返回指向这个值的iterator, 否则返回last,
An iterator to the lower bound of val in the range.
If all the element in the range compare less than val, the function returns last.
由于lower_bound是左闭右开的搜索,最后一个值未覆盖到,好在如果没找到回直接返回last,对lower_bound返回的值判断一下是否是target就可以覆盖对最后一个元素的搜索
int search(vector<int>& nums, int target)
{
static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr);
return 0; }();
auto it = lower_bound(nums.begin(),nums.end(),target);
return (it!=nums.end() && *it==target) ? it-nums.begin() : -1; //这里解决了val出现在最后的产生的问题
}
Reference
[LeetCode] 704. Binary Search的更多相关文章
- leetcode 704. Binary Search 、35. Search Insert Position 、278. First Bad Version
704. Binary Search 1.使用start+1 < end,这样保证最后剩两个数 2.mid = start + (end - start)/2,这样避免接近max-int导致的溢 ...
- LeetCode 704. Binary Search (二分查找)
题目标签:Binary Search 很标准的一个二分查找,具体看code. Java Solution: Runtime: 0 ms, faster than 100 % Memory Usage ...
- leetcode 153. Find Minimum in Rotated Sorted Array 、154. Find Minimum in Rotated Sorted Array II 、33. Search in Rotated Sorted Array 、81. Search in Rotated Sorted Array II 、704. Binary Search
这4个题都是针对旋转的排序数组.其中153.154是在旋转的排序数组中找最小值,33.81是在旋转的排序数组中找一个固定的值.且153和33都是没有重复数值的数组,154.81都是针对各自问题的版本1 ...
- LeetCode:Unique Binary Search Trees I II
LeetCode:Unique Binary Search Trees Given n, how many structurally unique BST's (binary search trees ...
- LeetCode: Validata Binary Search Tree
LeetCode: Validata Binary Search Tree Given a binary tree, determine if it is a valid binary search ...
- 【Leetcode_easy】704. Binary Search
problem 704. Binary Search solution: class Solution { public: int search(vector<int>& nums ...
- [LeetCode] 704. Binary Search_Easy tag: Binary Search
Given a sorted (in ascending order) integer array nums of n elements and a target value, write a fun ...
- [LeetCode] Closest Binary Search Tree Value II 最近的二分搜索树的值之二
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
- [LeetCode] Closest Binary Search Tree Value 最近的二分搜索树的值
Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...
随机推荐
- HDU 4396More lumber is required 过至少K条边的最短路
/* ** 题目要求过最少k条边的最短路 */ #include <iostream> #include <cstdio> #include <cstring> # ...
- CodeForces 821D Okabe and City
Okabe and City 题解: 将行和列也视为一个点. 然后从普通的点走到行/列的点的话,就代表这行/列已经被点亮了. 然后将费用为0的点建上边. 注意讨论(n,m)非亮的情况下. 代码: #i ...
- lightoj 1084 - Winter(dp+二分+线段树or其他数据结构)
题目链接:http://www.lightoj.com/volume_showproblem.php?problem=1084 题解:不妨设dp[i] 表示考虑到第i个点时最少有几组那么 if a[i ...
- ACM-ICPC 2017 Asia Urumqi:A. Coins(DP) 组合数学
Alice and Bob are playing a simple game. They line up a row of nn identical coins, all with the head ...
- CodeForces 311 B Cats Transport 斜率优化DP
题目传送门 题意:现在有n座山峰,现在 i-1 与 i 座山峰有 di长的路,现在有m个宠物, 分别在hi座山峰,第ti秒之后可以被带走,现在有p个人,每个人会从1号山峰走到n号山峰,速度1m/s.现 ...
- yzoj2057 x 题解
题意:给出一个集合,要求把这个集合分成两部分,使得一个集合中的任一元素都与另一个集合的全部元素都两两互质 暴力 枚举每个元素O(n^2)再暴力判gcd=1,如果非1就放入不同集合内,用并查集维护联通块 ...
- Python 之父的解析器系列之六:给 PEG 语法添加动作
原题 | Adding Actions to a PEG Grammar 作者 | Guido van Rossum(Python之父) 译者 | 豌豆花下猫("Python猫"公 ...
- Go pprof性能调优
在计算机性能调试领域里,profiling 是指对应用程序的画像,画像就是应用程序使用 CPU 和内存的情况. Go语言是一个对性能特别看重的语言,因此语言中自带了 profiling 的库,这篇文章 ...
- springboot打包jar包后运行
我们知道,spring boot内嵌tomcat,打包成jar包以后,直接就可以运行. 我们也可以使用启动项里面的mian入口来运行程序. 运行jar包时,我们一般是java -jar xxx.jar ...
- Dagger2 探索记1——四大基本组件(一)
喝很多自主学习的人,我接触Dagger 2 框架的原因是刚进公司的时候导师给安排的学习任务,学习方式是组内培训. 听到这个消息的我,以为是部门的人轮流给我讲课. 后来导师跟我说,组内培训的意思是,我先 ...