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. android network develop(1)----doing network background

    Develop network with HttpURLConnection & HttpClient. HttpURLConnection  is lightweight with Http ...

  2. [Jmeter]打开jmeter.bat报错的解决思路与方法

    解决过程: 打开apache-jmeter-3.0的jmeter.bat时,报错如下: 查看报错信息,应该是属于环境变量配置问题. 因此加上jave_home的路径语句在jmeter.bat文件上: ...

  3. oracle 得到新插入数据的ID并使用

    DECLARE  newID varchar2(50);begininsert into table1 (aa,bb) values('7777','8888') RETURNING ID INTO ...

  4. 利用mysql对特殊字符和超长字符会进行截断的特性 进行存储型XSS攻击——WordPress <4.1.2 & <=4.2 存储型xss

    转自:Baidu Security LabXteam http://xteam.baidu.com/?p=177 漏洞概述 本次漏洞出现两个使用不同方式截断来实现的存储型xss,一种为特殊字符截断,一 ...

  5. ASP.NET导出bdf文件

    1.导出助手类 using System;using System.IO;using System.Data;using System.Data.OleDb;using System.Web;usin ...

  6. 《HeadFirst设计模式》读后感——对学习设计模式的一些想法

    最近看完了<HeadFirst设计模式>,GOF的<设计模式——可复用面向对象软件的基础>的创建型模式也读完了,经历了从一无所知到茅塞顿开再到充满迷惑的过程. 不得不说< ...

  7. 【开学季】自学嵌入式开发|四核开发板|4412开发板|ARM+Android+linux技术

    淘宝店铺:迅为开发板http://arm-board.taobao.com 网站:http://www.topeetboard.com QQ咨询:2551456065 电话咨询:010-5895758 ...

  8. NOIP2013普及组 -SilverN

    T1  计数问题 题目描述 试计算在区间 1 到 n 的所有整数中,数字 x(0 ≤ x ≤ 9)共出现了多少次?例如,在 1 到 11 中,即在 1.2.3.4.5.6.7.8.9.10.11 中, ...

  9. TestNG之Factory

    如果我们的测试方法中,同一个变量需要很多个不同的测试数据,那么这些测试数据由谁提供呢,testng提供了factory的注解,下面我们来一探究竟. 一.单独使用Factory 1.新建一个含有@Fac ...

  10. jemter的使用(三)

    前面的文章已经把接口请求.响应等前序工作做好,那么如何施加压力呢,看下面 1.点击线程组,设置线程属性,其中:线程数即并发用户数,ramp-up period是多长时间初始化上面的并发用户数,循环次数 ...