描述:
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
代码实现(Java):(时间复杂度为 O(log n),使用二分法)
public int searchInsert(int[] A, int target) {
// write your code here
if (A == null || A.length == 0) {
return 0;
}
int start = 0, mid = 0, end = A.length - 1;
while (start <= end) {
mid = start + (end - start) / 2;
if (A[mid] == target) {
return mid;
} else if (A[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return start;
}