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:

  1. You may assume that all elements in nums are unique.
  2. n will be in the range [1, 10000].
  3. The value of each element in nums will 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

  1. lower_bound - C++ Reference

[LeetCode] 704. Binary Search的更多相关文章

  1. 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导致的溢 ...

  2. LeetCode 704. Binary Search (二分查找)

    题目标签:Binary Search 很标准的一个二分查找,具体看code. Java Solution: Runtime:  0 ms, faster than 100 % Memory Usage ...

  3. 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 ...

  4. LeetCode:Unique Binary Search Trees I II

    LeetCode:Unique Binary Search Trees Given n, how many structurally unique BST's (binary search trees ...

  5. LeetCode: Validata Binary Search Tree

    LeetCode: Validata Binary Search Tree Given a binary tree, determine if it is a valid binary search ...

  6. 【Leetcode_easy】704. Binary Search

    problem 704. Binary Search solution: class Solution { public: int search(vector<int>& nums ...

  7. [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 ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. vmware上安装的ubuntu连接不上网络

    解决方法如下: 1.右键点击ubuntu,选择“设置” 2.网络适配器设置为“仅主机模式”:与主机共享的专用网络.点击“确定”即可.

  2. 同步vmware虚拟机和主机的时间

    1. 打开虚拟机->设置 2. 选择选项标签页,选中VMware Tools,勾选“将客户机时间与主机同步”

  3. POJ-1847 Tram( 最短路 )

    题目链接:http://poj.org/problem?id=1847 Description Tram network in Zagreb consists of a number of inter ...

  4. 堆实战(动态数据流求top k大元素,动态数据流求中位数)

    动态数据集合中求top k大元素 第1大,第2大 ...第k大 k是这群体里最小的 所以要建立个小顶堆 只需要维护一个大小为k的小顶堆 即可 当来的元素(newCome)> 堆顶元素(small ...

  5. Go语言基础之网络编程

    现在我们几乎每天都在使用互联网,我们前面已经学习了如何编写Go语言程序,但是如何才能让我们的程序通过网络互相通信呢?本章我们就一起来学习下Go语言中的网络编程. 关于网络编程其实是一个很庞大的领域,本 ...

  6. Salesforce LWC学习(七) Navigation & Toast

    上一篇我们介绍了针对LWC中常用的LDS的适配的wire service以及@salesforce模块提供的相关的service,其实LWC中还提供其他的好用的service,比如针对导航相关的lig ...

  7. IntelliJ IDEA 设置 vue 支持

    一.IntelliJ IDEA支持.vue文件 安装vue.js file --> settings --> plugins,输入vue,点击搜索结果里的vue.js右边的install按 ...

  8. jstat虚拟机统计信息监视工具

    jstsat(JVM Statistics Monitoring Tool) jstat用于监视虚拟机各种运行状态信息的命令工具.可以显示本地或者远程虚拟机进程中的类装载.内存.垃圾收集.JIT编译等 ...

  9. 在线扩容LV卷

    1.登陆VC,添加硬盘 2.登陆到Linux主机 3.在线扫盘 [root@cnsz22pl0074:/root]# echo "- - -" > /sys/class/sc ...

  10. Unity3D_01_各种寻找GameObject方法

    1.GameObject.Find(): 寻找Hierarchy面板中的activie 不为false的游戏对象: 路径如官方事例写法: public class ExampleClass : Mon ...