首页 > 其他 > 详细

Search Insert Position

时间:2015-03-04 16:12:53      阅读:258      评论:0      收藏:0      [点我收藏+]

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.

思路:

二分查找问题

我的代码:

技术分享
public class Solution {
    public int searchInsert(int[] A, int target) {
        if( A == null || A.length == 0) return -1;
        int left = 0;
        int right = A.length - 1;
        while(left <= right)
        {
            int mid = (left + right)/2;
            if(A[mid] == target)    return mid;
            else if(A[mid] > target)    right = mid - 1;
            else left = mid + 1;
        }
        return left;
    }
}
View Code

学习之处:

  • 二分查找left≤right
  • 二分查找停止循环时候的left和right的位置 想想真是公平哒,刚开始left < right,退出循环的话,left指向大的数据,right指向小的数据

技术分享

 

Search Insert Position

原文:http://www.cnblogs.com/sunshisonghit/p/4313581.html

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