博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】 search Insert Position(middle)
阅读量:6941 次
发布时间:2019-06-27

本文共 648 字,大约阅读时间需要 2 分钟。

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

 

思路:

与普通二分搜索的唯一区别在于 可能插入的位置是没找到时 l 的值

int searchInsert(int A[], int n, int target) {    int l = 0, r = n - 1;    while(l <= r)    {        int m = (l + r) / 2;        if(A[m] == target)            return m;        else if(A[m] > target)            r = m - 1;        else            l = m + 1;    }    return l;       //注意 就这里不一样  最后r = l - 1 返回l就可以了 就是应该插入的位置}

 

转载地址:http://uuinl.baihongyu.com/

你可能感兴趣的文章
date 修改系统时间
查看>>
python coroutine的学习跟总结[转]
查看>>
String 的扩展方法
查看>>
[zhuan]Simple Emacs Configuration
查看>>
Flex Builder 3 下载与注册
查看>>
【存储方式】SharedPreference
查看>>
[转载]wp7
查看>>
WCF初见之HelloWorld
查看>>
无限循环小数怎么换成分数形式
查看>>
抄袭一点linux的经典资料
查看>>
ASP.net MVC: 一个开源的“留言系统”
查看>>
HTTP的请求头标签 If-Modified-Since
查看>>
阻塞和死锁问题整理一
查看>>
Android 时间日期Widget 开发详解
查看>>
[置顶] java 通过classloader加载类再通过classforname实例化
查看>>
Google Web Designer – 创建引人入胜的 HTML5 网站
查看>>
Qt5中的QtGui
查看>>
动态链接库(dll)简介(转)
查看>>
将某个组中的账户移动到新的OU下
查看>>
值得珍藏的资料--触摸技术的发展史(转)
查看>>