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. 2019牛客暑期多校训练营(第二场)J-Subarray(思维)

    >传送门< 前言 这题我前前后后看了三遍,每次都是把网上相关的博客和通过代码认真看了再思考,然并卵,最后终于第三遍也就是现在终于看懂了,其实懂了之后发现其实没有那么难,但是的的确确需要思维 ...

  2. 菜鸟系列Fabric——Fabric 动态添加组织(7)

    Fabric 网络动态添加组织 1.环境准备 如果存在fabric网络环境可不执行,若不存在可以安装下列进行准备 下载fabric-sample,fabric https://github.com/h ...

  3. NPOI导出Excel封装

    直接上代码 public class ExcelUtils { public static ICellStyle CreateStyle(IWorkbook workbook, string font ...

  4. Java 网络编程:必知必会的 URL 和 URLConnection

    java.net.URL 类将 URL 地址进行了封装,并提供了解析 URL 地址的基本方法,比如获取 URL 的主机名和端口号.java.net.URLConnection 则代表了应用程序和 UR ...

  5. mysql之innodb日志管理

    本文从两个方面进行阐述,常规的日志文件(不区分存储引擎),第二就是讲innodb存储引擎的事务日志. 一.基本日志文件 1.1.基本日志文件分类:错误日志(error log)慢查询日志日志(slow ...

  6. Python字符串中删除特定字符

    分析 在Python中,字符串是不可变的.所以无法直接删除字符串之间的特定字符. 所以想对字符串中字符进行操作的时候,需要将字符串转变为列表,列表是可变的,这样就可以实现对字符串中特定字符的操作. 1 ...

  7. 【Offer】[28] 【对称的二叉树】

    题目描述 思路分析 测试用例 Java代码 代码链接 题目描述 请实现一个函数,用来判断一-棵二叉树是不是对称的.如果一棵二叉树和它的镜像一样,那么它是对称的.  牛客网刷题地址 思路分析 利用前序 ...

  8. 通过脚本实现将服务器的Log实时传送到Telegram群组

    首先说下需求,IT老大提出的一个需求,实现将php-laravel的应用日志实时传送到telegram的监控群组中,不用登陆服务器就可以实时查看应用的日志. 具体思路是: 先要将日志切割,并实时更新这 ...

  9. Java中ElasticSearch的删除示例

    public class DeleteElasticAPI { private static RestClient restClient; static { restClient=RestClient ...

  10. android 之图片异步加载

    一.概述 本文来自"慕课网" 的学习,只是对代码做一下分析 图片异步加载有2种方式:  (多线程/线程池) 或者 用其实AsyncTask , 其实AsyncTask底层也是用的多 ...