Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

这就是普通的二分查找,需要注意的地方代码注释中都有。其中特别注意的是:middle=(low+high)/ 2 ,可能会溢出,可以替换为middle = low + ((high - low)>>2);

class Solution {
public:
int searchInsert(int A[], int n, int target) {
//二分查找
int low = 0, high = n-1;//注意这里high是初始化为n-1
while(low <= high)//注意这里是<=号
{
//int middle = (low + high) / 2;
int middle = low + ((high - low)>>2); //可以防止low + high 溢出
if(A[middle] < target)
low = middle + 1;
else if(A[middle] > target)
high = middle - 1;
else return middle;
}
return low;//注意返回值是low
}
};

根据程序员编程艺术第二十五章:Jon Bentley:90%无法正确实现二分查找, 如果high初始化为n, 那么while判断语句就应该是low<high, 下面的A[middle] > target分支中,就应该是high = middle


Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,

return [3, 4].

看到这个有没有想到STL中的equal_range函数,这个函数是调用lower_boundupper_bound, 下面我们仿照STL的实现。相比上一题的二分查找,lower_bound当A[middle] == target时,继续向左半部分查找,它返回的是第一个不小于目标数的元素位置;upper_bound当A[middle] == target时,继续向右半部分查找,它返回的是第一个大于目标数的元素位置。    本文地址

class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> res(2, -1);
int low = 0, high = n-1;
while(low <= high)
{
int middle = low + ((high - low)>>2);
if(A[middle] < target)
low = middle + 1;
else if(A[middle] > target)
high = middle - 1;
else
{
res[0] = lowerBound(A, low, middle - 1, target);
res[1] = upperBound(A, middle + 1, high, target) - 1;
return res;
}
}
return res;
} //找到范围内[left,right]内第一个不小于target的元素
int lowerBound(int A[], int left, int right, int target)
{
int low = left, high = right;
while(low <= high)
{
int middle = low + ((high - low)>>2);
if(A[middle] < target)
low = middle + 1;
else high = middle - 1;
}
return high + 1;//注意这里返回值不是low
}
//找到范围[left,right]内第一个大于target的元素
int upperBound(int A[], int left, int right, int target)
{
int low = left, high = right;
while(low <= high)
{
int middle = low + ((high - low)>>2);
if(A[middle] <= target)
low = middle + 1;
else high = middle - 1;
}
return low;
}
};

【版权声明】转载请注明出处http://www.cnblogs.com/TenosDoIt/p/3681677.html

LeetCode:Search Insert Position,Search for a Range (二分查找,lower_bound,upper_bound)的更多相关文章

  1. [Leetcode][Python]35: Search Insert Position

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 35: Search Insert Positionhttps://oj.le ...

  2. [array] leetcode - 35. Search Insert Position - Easy

    leetcode - 35. Search Insert Position - Easy descrition Given a sorted array and a target value, ret ...

  3. [LeetCode] 035. Search Insert Position (Medium) (C++)

    索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 035. Sea ...

  4. Leetcode之二分法专题-35. 搜索插入位置(Search Insert Position)

    Leetcode之二分法专题-35. 搜索插入位置(Search Insert Position) 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引.如果目标值不存在于数组中,返回它将会 ...

  5. LeetCode练题——35. Search Insert Position

    1.题目 35. Search Insert Position Easy 1781214Add to ListShare Given a sorted array and a target value ...

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

  7. LeetCode: Search Insert Position 解题报告

    Search Insert Position Given a sorted array and a target value, return the index if the target is fo ...

  8. 【LeetCode】35. Search Insert Position (2 solutions)

    Search Insert Position Given a sorted array and a target value, return the index if the target is fo ...

  9. Leetcode 二分查找 Search Insert Position

    本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie Search Insert Position Total Accepted: 14279 T ...

随机推荐

  1. java 之 对象与垃圾回收

    1.垃圾回收机制只负责回收堆内存中的对象,不会回收任何物理资源(如数据库连接,网络IO等资源) 2.程序无法精确控制垃圾回收的运行,垃圾回收会在合适的时候运行.当对象永久的失去引用后,系统会在合适的时 ...

  2. SQL Server智能感知如何更新

    经常用sql server发现一个问题,比如说我刚刚添加个表或者字段,这时候在sqlserver里面写sql语句时,没有智能提示,这个问题我以前一直不是太注意.今天好好找了下解决方法,这里做下分享. ...

  3. android textview 设置不同的颜色和大小

    1.定义不同的style <style name="approval_detail_info_style1"> <item name="android: ...

  4. Handler与Looper,MessageQueue的关系

    总结一下Handler与Looper,MessageQueue的关系,并实现自定义与子线程相关的Handler. 一.Handler与Looper,MessageQueue的关系 它们之间的关系其实就 ...

  5. Flash网站Loading制作

    Flash网站Loading制作~~~ stop(); stage.scaleMode=StageScaleMode.NO_SCALE; //指定舞台属性为不跟随播放器大小而改变 stage.show ...

  6. Effective Java 60 Favor the use of standard exceptions

    Benefits to reuse preexisting exceptions It makes your API easier to learn and use. Programs using y ...

  7. 《SQL Server企业级平台管理实践》读书笔记——几个系统库的备份与恢复

    master数据库 master作为数据库的主要数据库,记录着SQL Server系统的所有系统级信息,例如登录用户.系统配置设置.端点和凭证以及访问其他数据服务器所需要的信息.master数据库还记 ...

  8. loadrunner常用函数

    1.关联函数:web_reg_save_param("session", "LB=value=", "RB=>", LAST);

  9. std::list

    1遍历 std::list<TYPE*>::const_iterator iter_list; for (iter_list = my_list.begin(); iter_list != ...

  10. Watchdog

    一.简介 Watchdog主要用于监视系统的运行,Linux内核不仅为各种不同类型的watchdog硬件电路提供了驱动,还提供了一个基于定时器的纯软件watchdog驱动. 驱动源码位于内核源码树dr ...