LeetCode 118 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

分析:

二分查找,不同点就是开始时判断target与两边界点的关系

public class Solution {
    public int searchInsert(int[] A, int target) {
        //二分查找
        return searchInsert(A, target, 0, A.length-1);
    }
    
    public int searchInsert(int[] A, int target, int start, int end){
        if(target < A[start]) return start;
        if(target > A[end]) return end+1;
        int mid = (start+end)/2;
        if(target == A[mid]) return mid;
        if(target < A[mid])
            return searchInsert(A, target, start, mid-1);
        else
            return searchInsert(A, target, mid+1, end);
    }
}


你可能感兴趣的:(LeetCode,search,insert,Positi)