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

注意例子给的很好,自己要想到

Code 1

简洁

public class Solution {
    public int searchInsert(int[] nums, int target) {
        int low =0, hi = nums.length;
        while (low < hi){
            int mid = low + (hi-low)/2;
            if (nums[mid] == target) {return mid;}
            else if (nums[mid] < target) {low = mid+1;}
            else {hi = mid;}
        }
        return low;
    }
}

Code 2

长一点,不容易出错

public class Solution {
    public int searchInsert(int[] nums, int target) {
        if (nums == null || nums.length==0) return 0;
        int start = 0, end = nums.length-1;
        while (start + 1 < end){
            int mid = start + (end - start)/2;
            if (nums[mid] == target){
                return mid;
            }
            else if (nums[mid] > target){
                end = mid;
            }
            else {
                start = mid;
            }
        }

        if (nums[start] >= target) return start;
        if (nums[end] < target) return end+1;
        return end;
    }
}