Sorted 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
思路:

binary search。。。We want to find the biggest index such that a[index] <= target.
For example, 
   r l
[1,3,5,6], 5 → 2
when the while loop terminates, we want l to be that index. To get that, when target <= a[mid], we keep looking at the left half of the array, meaning we set r = mid - 1, otherwise target > a[mid], and we set l = mid + 1.

Solution:

Time: O(logn)
Space: O(1)

public class Solution {
    public int searchInsert(ArrayList<Integer> a, int b) {
        //    r l
        //  1 3 5 6, 5
        //  r l  
        //  1 3 5 6, 2
        //r l
        //  1 3 5 6, 0
        
        // if b <= mid, r = mid - 1
        // else l = mid + 1
        
        int left = 0;
        int right = a.size() - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (b <= a.get(mid)) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
}