首页 > 其他 > 详细

[Leetcode]-- Search Insert Position

时间:2014-02-08 09:15:22      阅读:363      评论:0      收藏:0      [点我收藏+]

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

参考 : http://www.cnblogs.com/feiling/p/3232368.html

二分搜索,如search到则返回,否则将target与二分搜索循环终止处的数进行比较:

二分搜索循环终止时:l==r

当A[l] >= target时,将target插入到l之前,如line 20,之前考虑相等时将该数放在l之后,但有个test case没跑过去([1], 1 expected: 0)

否则放在l之后

bubuko.com,布布扣
 1 public class Solution {
 2     public int searchInsert(int[] A, int target) {
 3         int len = A.length;
 4         int l = 0;
 5         int r = len-1;
 6         while(l < r){
 7             int m = (l+r)/2;
 8             if(A[m] == target){
 9                 return m;
10             }else if(A[m] < target){
11               l = m +1;   
12             }else{
13                 r = m-1;
14             }
15         }
16         
17         if(A[l] >= target){
18             return l;
19         }else{
20             return l+1;
21         }
22     }
23 }
View Code

[Leetcode]-- Search Insert Position

原文:http://www.cnblogs.com/RazerLu/p/3540022.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!