Search Insert Position

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指向小的数据

 

if(null==nums || nums.length==0) return -1;
int left = 0;
int right = nums.length - 1;

while(left <= right){
int mid = (left+right)/2;
if(target == nums[mid]) return mid;
if(target > nums[mid]) left = mid+1;
if(target < nums[mid]) right = mid-1;
}

return left;

posted on 2015-03-04 15:55  zhouzhou0615  阅读(142)  评论(0编辑  收藏  举报

导航