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

跟定一个有序数组和一个目标,如果目标在数组里找到目标的下标,如果不在,找到目标应该插入的位置。

二分查找,找到则返回mid,否则返回r+1或则l。

class Solution {
public:
int searchInsert(int A[], int n, int target)
{
if (n == 0)
return 0;
int l = 0, r = n - 1, mid = 0;
while(l <= r)
{
mid = (l + r) / 2;
if (A[mid] == target)
return mid;
if (A[mid] < target)
l = mid + 1;
else
r = mid - 1;
}
return l; // 返回的是l,或者是r+1
}
};

2015/03/31:

从左到右找到相等的或者找到第一次比target大的数的位置即为插入下标位置,但这个是On的,python如下:

class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return integer
def searchInsert(self, A, target):
for i in range(len(A)):
if A[i] == target or A[i] > target:
return i
return len(A)

还是用第一种 二分法快吧

最新文章

  1. ecshop编辑器FCKeditor修改成KindEditor编辑批量上传图片
  2. Delphi 操作Flash D7~XE10都有 导入Activex控件 shockwave
  3. [OC] 理解Bitcode:一种中间代码
  4. 【Linux命令】之fc,手动安装字体
  5. Hive conf issue
  6. DW(五):polybase集群安装
  7. Git - Tutorial官方【转】
  8. C++模板详解
  9. axure7.0 汉化包下载
  10. win7家庭版任务栏预览消失,只显文字终极解决法
  11. 播放器音乐源之天天动听API
  12. struts2笔记08-初识ActionSupport
  13. ice grid 第一篇
  14. 转换编码,将Unicode编码转换成可以浏览的utf-8编码
  15. SetConsoleScreenBufferSize 函数--设置控制台屏幕缓冲区大小
  16. LintCode主元素
  17. Holiday、Vacation、Days off、Leave、Break
  18. Atitit 常用sdk 模块 组织架构切分 规范与范例attilax总结
  19. java调用执行cmd指令启动weblogic
  20. 【LOJ】#2080. 「JSOI2016」病毒感染

热门文章

  1. Docker简介(转)
  2. 编写高质量JavaScript代码绳之以法(The Essentials of Writing High Quality JavaScript)翻译
  3. CloudFoundry.yml修订
  4. iis7、iis8配置备份还原
  5. 自动注册 IIS6 的 MIME 类型
  6. hdu 1025 Constructing Roads In JGShining’s Kingdom 【dp+二分法】
  7. 《C++ Primer Plus》学习笔记10
  8. WP 前台或后台显示ShellToast
  9. 我的Linux学习历程:那些我看过的Linux书籍们
  10. 栈 &lt;stack&gt;