Friday, March 8, 2013

[LeetCode] Search Insert Position

Thought:
It is actually finding how many numbers are smaller than target.

Code:
public class Solution {
    public int searchInsert(int[] A, int target) {
        return helper(A, target, 0, A.length - 1);
    }
    public int helper(int[] A, int target, int start, int end) {   
        if (start >= end) return A[start] >= target ? 0 : 1;
        int mid = (start + end) / 2;
        if (A[mid] == target) return mid - start;
        if (A[mid] > target) return helper(A, target, start, mid - 1);
        return mid - start + 1 + helper(A, target, mid + 1, end);
    }
}

No comments:

Post a Comment