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

SOLUTION 1:

用九章算法的模板查找结束后判断一下即可。:

 public int searchInsert1(int[] A, int target) {
if (A == null || A.length == 0) {
return 0;
} int left = 0;
int right = A.length - 1; while (left < right - 1) {
int mid = left + (right - left) / 2;
int num = A[mid]; if (num == target) {
return mid;
} else if (num < target) {
left = mid + 1;
} else {
right = mid - 1;
}
} // bug 1: should use <=
if (target <= A[left]) {
return left;
// bug 2: should use <= . consider that may the result exit in left or right.
} else if (target <= A[right]) {
return right;
} return right + 1;
}

SOLUTION 2:

也可以很简洁:

http://fisherlei.blogspot.com/2013/01/leetcode-search-insert-position.html

http://blog.csdn.net/fightforyourdream/article/details/14216321

这样可以word的原因是:

1. 当target存在,当然返回mid.

2. 当target大于所有的数。则l, r会跑到最右边,并且l会继续跑出去一格,也就是l会指向 len,也就是要找的值。

3. 当target小于所有的数。l,r跑到最左边,并且r会继续往左移动一格,l指向目标位置。

4. 当target小于某数a,并大于某数b。那么l, r中止时,r会在b,l 会在a,l 指向目标位置。

若是找不到target, 循环结束后l 的值是 与target最接近但是 > target 的数在数组中的位置。

 // sol 2:
public int searchInsert(int[] A, int target) {
if (A == null || A.length == 0) {
return 0;
} int left = 0;
int right = A.length - 1; while (left <= right) {
int mid = left + (right - left) / 2;
int num = A[mid]; if (num == target) {
return mid;
} else if (num < target) {
left = mid + 1;
} else {
right = mid - 1;
}
} return left;
}

GTIHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/divide2/SearchInsert.java

最新文章

  1. OPP Services Log
  2. python day1:初识Python(一)
  3. html理解
  4. JS网页顶部弹出可关闭广告图层
  5. linux服务器init 5启动图形界面,报错Retrigger failed udev events
  6. CentOS 6.5 安装 Python3
  7. 开发ERP软件应该遵守的22条规则
  8. 进程间通信之打开关闭一个exe文件
  9. POJ 2031 Building a Space Station (最小生成树)
  10. Winodws live writer
  11. Base64的用法
  12. JavaScript中String对象的match()、replace() 配合正则表达式使用
  13. MojoliciousLite: 实时的web框架 概述
  14. karma+jasmine自动化测试
  15. Angular2组件与指令的小实践
  16. JS的基本类型(小知识)
  17. 解决SVN Cleanup错误: Failed to run the WC DB work queue associated with
  18. python timeit模块用法
  19. d3.js,初遇
  20. AL32UTF8 and UTF8 and ZHS16GBK

热门文章

  1. lu协程练习
  2. [aaronyang] nodejs学习-mongodb[1]
  3. SQLServer2008 全文检索摘记
  4. &#39;Agent XPs&#39; component is turned off as part of the security configuration for this server
  5. SharePoint自动化部署,利用SPSD工具包
  6. asp.net中C#中计算时间差代码
  7. PHP与MYSQL中UTF8 中文排序例子
  8. 【转载】java前后端 动静分离,JavaWeb项目为什么我们要放弃jsp?
  9. django form 对象is_bound属性
  10. curl以cookie的方式登录