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. swift网络编程入门应用:天气预报

    学习来自<小波说雨燕 第二季 网络编程(入门篇)> 工具:xcode6.4 首先在Main.storyborad中添加并设置好三个label做简单的界面显示: import UIKit / ...

  2. 21分钟 MySQL 入门教程

    目录 一.MySQL的相关概念介绍 二.Windows下MySQL的配置 配置步骤 MySQL服务的启动.停止与卸载 三.MySQL脚本的基本组成 四.MySQL中的数据类型 五.使用MySQL数据库 ...

  3. redis高可用之REDIS SENTINEL

    1. Redis主从配置 1.1. 设置主从复制 Master <= Salve 10.24.6.5:6379 <= 10.24.6.7:6379 1.2.   取消主从复制 1.3.   ...

  4. Cocos2d-x解析XML文件,解决中文乱码

    身处大天朝,必须学会的一项技能就是解决中文显示问题.这个字符问题还搞了我一天,以下是个人解决乱码问题的实践结果,希望可以给其他人一些帮助 读取xml文件代码: CCDictionary* messag ...

  5. Azure 上为Liunx VM 挂载File类型的存储。

    1. Create a storage account in Azure, copy the storage account endpoint URL (with postfix of "f ...

  6. Hive query issue

    One time, I have written a query with two tables join, One table is big table with partitions , anot ...

  7. docker containerd shim分析

    // containerd-shim is a small shim that sits in front of a runtime implementation that allows it to ...

  8. 【读书笔记《Android游戏编程之从零开始》】15.游戏开发基础(剪切区域)

    剪切区域也称为可视区域,是由画布进行设置的:它指的是在画布上设置一块区域,当画布一旦设置了可视区域,那么除此区域外,绘制的任何内容都将看不到:可视区域可以是圆形.矩形等等. 画布提供了三种设置可视区域 ...

  9. 边工作边刷题:70天一遍leetcode: day 86-2

    Best Meeting Point 要点: 题本身不难理解,manhattan distance.follow up就变成weighted了(因为一个地方可以有多个住户) 注意input是grid的 ...

  10. HDU 5102 The K-th Distance

    题意:给你n-1条边,然后没两个节点的距离按照递增的顺序,求出前k项的和. 官方题解: 把所有边(u,v) 以及(v,u)放入一个队列,队列每弹出一个元素(u,v),对于所有与u相邻的点w,如果w!= ...