leetcode: Search Insert Position

题目:

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

 解决:

/**
 * 使用两分法查找
 * @author Administrator
 *
 */
public class SearchInsert {
	public int searchInsert(int[] A, int target) {
		if (A == null || A.length == 0)
			return 0;
		int end = A.length - 1;
		return search(A, 0, end, target);
	}

	int search(int[] A, int start, int end, int t) {
		if (start == end) {
			if (t == A[start])
				return start;
			else if (t > A[start])
				return start + 1;
			else
				return start;
		}
		int m = (end - start) / 2 + start;
		if (t == A[m]) {//找到了
			return m;
		} else if (t < A[m]) {//目标在start到m之间
			return search(A, start, m, t);
		} else {//目标在m+1到end之间
			return search(A, m + 1, end, t);
		}
	}
}

 

点赞