[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 ...
随机推荐
- python中,一个函数想使用另一个函数中的变量
问题: 第一个函数中用到了变量a:第二个函数也想使用变量a. 解决方法: 在第一个函数中将变量a定义为全局变量,然后在第二个函数中,也写上global a即可. 示例: def func1(): gl ...
- hdu 5534 Partial Tree(完全背包)
题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=5534 题解:这题一看有点像树形dp但是树形dp显然没什么思路.然后由于这里的约束几乎没有就 ...
- 模板汇总——AC自动机
AC自动机 模板题 HDU-2222 Keywords Search #include<bits/stdc++.h> using namespace std; #define LL lon ...
- ZOJ 3870 Team Formation 位运算 位异或用与运算做的
For an upcoming programming contest, Edward, the headmaster of Marjar University, is forming a two-m ...
- java基础面试(二)
最近有搜了几个面试题,大家一起来探讨一下. 1.Oracle 的分页 --分页查询一 select * from (select a1.*,rownum rn from (select * from ...
- Swift从入门到精通第八篇 - 方法 初识
方法(学习笔记) 环境Xcode 11.0 beta4 swift 5.1 方法 结构体.枚举.类都可以定义方法(实例方法.类型方法) 实例方法(Instance Methods) 实例方法只能用实例 ...
- java多线程之Executor框架
Executor框架简介 Executor框架的结构 Executor框架主要由3大部分组成: 任务: 包括被执行的任务需要实现的接口:Runable 接口.Callable接口: 任务的执行: 包括 ...
- 未能加载文件或程序集“Renci.SshNet, Version=2016.1.0.0, Culture=neutral, PublicKeyToken=……”
emmmm~ 这是一个让人烦躁有悲伤的问题~ 背景 我也不知道什么原因,用着用着,正好好的,就突然报了这种问题~ 未能加载文件或程序集“Renci.SshNet, Version=2016.1.0.0 ...
- Winforn中DevExpress的TreeList中显示某路径下的所有目录和文件(附源码下载)
场景 Winform中DevExpress的TreeList的入门使用教程(附源码下载): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...
- iOS -打包上传成功,在"构建版本"一直刷不出来
今天提交版本到appstore,构建版本一直不出来,等了一天也没有出来,其实就是权限问题,iOS13 来了,所以面临的问题随之而来,苹果给邮箱发了这段话: Dear Developer,We iden ...