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. P1640 [SCOI2010]连续攻击游戏 二分图构造

    https://www.luogu.org/problemnew/show/P1640 题意 lxhgww最近迷上了一款游戏,在游戏里,他拥有很多的装备,每种装备都有2个属性,这些属性的值用[1,10 ...

  2. CodeForces 1084 F Max Mex

    Max Mex 题意:问在树上的所有路中mex值最大是多少. 题解: 用线段树维护值. 区间[L,R]意味着 区间[L,R]的数可不可以合并. 重点就是合并的问题了. 首先合法的区间只有3种: 1. ...

  3. CSS3 04. 伸缩布局、设置主轴,侧轴方向、主/侧轴对齐方式、 伸缩比例、元素换行、换行控制、覆盖父元素的align-items;控制子元素顺序、web字体、突变字体

    CSS3 在布局方面做了非常大的改进,对块级元素的布局排列变得十分灵活,适应性非常强,其强大的伸缩性,在响应式开发中可以发挥极大的作用.(兼容性不好) 必要元素: 指定一个盒子为伸缩盒子 displa ...

  4. 【Offer】[58-2] 【左旋转字符串】

    题目描述 思路分析 测试用例 Java代码 代码链接 题目描述 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部.请定义一个函数实现字符串左旋转操作的功能.比如,输入字符串"a ...

  5. Leetcode:合并两个有序链表

    class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) { return ...

  6. java8函数式接口详解、函数接口详解、lambda表达式匿名函数、方法引用使用含义、函数式接口实例、如何定义函数式接口

    函数式接口详细定义 函数式接口只有一个抽象方法 由于default方法有一个实现,所以他们不是抽象的. 如果一个接口定义了一个抽象方法,而他恰好覆盖了Object的public方法,仍旧不算做接口的抽 ...

  7. ORM之Dapper运用

    一.前言 上一篇[分层架构设计]我们已经有了架构的轮廓,现在我们就在这个轮廓里面造轮子.项目要想开始,肯定先得确定ORM框架,目前市面上的ORM框架有很多,对于.net人员来说很容易就想到以ADO.N ...

  8. vuex-class用法

    vuex-class可以包装vuex的写法,使代码简化 Installation $ npm install --save vuex-class Example import Vue from 'vu ...

  9. 行内元素有哪些?块级元素有哪些?空(void)元素有哪些?

    CSS规范规定,每个元素都有display属性,确定该元素的类型.每个元素都有默认的display值,如div的display默认值为“block”,则为“块级”元素:span默认display属性值 ...

  10. 【第十四篇】easyui datagrid导出excel

    <a class="btn btn-app" onclick="exportExcel()"><i class="fa fa-edi ...