题目:
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);
}
}
}
本文介绍了一种使用二分查找算法解决特定问题的方法。该算法应用于已排序的数组中查找目标值的位置,若未找到则返回目标值按序插入的位置。通过递归方式实现了高效的搜索过程。
176

被折叠的 条评论
为什么被折叠?



