public int searchInsert(int[] A, int target) {
if (A == null || A.length == 0) {
return -1;
}
int start = -1, end = A.length;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] == target) {
return mid; // no duplicates
} else if (A[mid] < target) {
start = mid;
} else {
end = mid;
}
}
return start + 1;
}
}Search Insert position( 二分查找)
本文介绍了一个二分查找算法的应用实例——在一个有序数组中找到指定元素的插入位置。该算法首先检查数组是否为空或为null,然后设定初始搜索范围,并通过循环逐步缩小搜索区间直至找到目标位置。

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



