[leetcode]Search Insert Position

二分查找的小变化。简单题。

public class Solution {

    public int searchInsert(int[] A, int target) {

        // Start typing your Java solution below

        // DO NOT write main() function

        return searchInsert(A, target, 0, A.length - 1);

    }

    

    public int searchInsert(int[] A, int target, int left, int right) {

        int mid = (left + right) / 2;

    	if (A[mid] == target) return mid;

    	

    	if (A[mid] < target) {

    		if (mid+1 > right) {

    			return mid+1;

    		}

    		return searchInsert(A, target, mid+1, right);

    	}

    	else // A[mid] > target 

    	{

    		if (mid-1 < left){

    			return mid;

    		}

    		return searchInsert(A, target, left, mid-1);

    	}

    }

}

  

你可能感兴趣的:(LeetCode)