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

题意:在已排序的数组中查找给定数字,若有,返回下标,没有,则返回插入位置

思路:题意的要求应该理解成,应该返回的是第一个不小于目标值的下标。所以用二分查找即可。详情可见我之前的博客关于二分查找的总结。代码如下:

 class Solution {
public:
int searchInsert(int A[], int n, int target)
{
int lo=,hi=n;
while(lo<hi)
{
int mid=lo+((hi-lo)>>);
if(A[mid]<target)
lo=mid+;
else
hi=mid;
}
return hi;
}
};

最新文章

  1. JS 生成GUID 方法
  2. C++ 虚函数,纯虚函数的一些问题
  3. 音频文件解析(一):WAV格式文件头部解析
  4. Hibernate和Mybatis的对比
  5. 转载:开发者眼中最好的 22 款 GUI 测试工具
  6. WCF入门(22)
  7. eclipse 每次切换工作空间都要重新配置
  8. paip.android 手机输入法制造大法
  9. mongodb 新建用户 -摘自网络
  10. Android 各个版本WebView
  11. C# 创建验证码图片
  12. HDU 5428 The Factor (素因数分解)
  13. ETL实践--kettle转到hive
  14. web 服务器、PHP、数据库、浏览器是如何实现动态网站的
  15. tensorflow-Inception-v3模型训练自己的数据代码示例
  16. Linux配置防火墙端口 8080端口
  17. MVC AOP解决JsonResult返回json时间格式
  18. 微信小程序 自定义单选复选按钮组的实现(用于实现购物车产品列表功能)
  19. LeetCode-Microsoft-Clone Graph
  20. node 本地静态服务器

热门文章

  1. “腾讯WeTest助力《龙珠直播》盘点APP质量问题”
  2. system_Class类说明文档
  3. 打印队列 (Printer Queue,ACM/ICPC NWERC 2006,UVA12100)
  4. 从零开始的Python学习Episode 1
  5. codeforces 319B Psychos in a Line(模拟)
  6. 自测之Lesson13:共享内存
  7. Greedy Gift Givers 贪婪的送礼者
  8. “Hello World!”团队召开的第十二次会议
  9. 第二次作业 编程题 PAT 1001A+B Format
  10. TCP系列13—重传—3、协议中RTO计算和RTO定时器维护