前端bubucuo前端算法实战
public class BinarySearch {
public int binarySearch(int target, int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) { // 相邻即退出
int mid = start + (end - start) / 2; // 可以防止两个整型值相加时溢出
if (target > nums[mid]) { // 如果数组中有多个 target,此时找到的是最左侧的,即相等时移动的是 end。如果要找最右侧的,那么相等时移动 start 即可
start = mid;
} else {
end = mid;