public static int binSearch(int[] arr, int key) {
int left = 0;
int right = arr.length - 1;
int mid = 0;
while (left <= right) {
// 如果left与right都超过了int最大值的1/2,那么(left+right)会发生溢出,
// 因此不能使用(left+right)/2求mid,而是应该用left+(right-left)/2
mid = left + (right - left) / 2;
if (key < arr[mid]) {
right = mid - 1;
} else if (key > arr[mid]) {
left = mid + 1;
} else {
return mid;
}
}
return -1;
}
/**
* 解法1:遍历数组,查找缺失的数字
*/
public int missingNumber(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] != i) {
return i;
}
}
return nums.length;
}
/**
* 解法二:使用二分法查找丢失数字
*/
public int missingNumberBinarySearch(int[] nums) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (left - right) / 2;
if (nums[mid] == mid) { // 说明缺失的数字不在前半段数组
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
public int searchInsert(int[] nums, int target) {
int left = 0, right = nums.length - 1, mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (target < nums[mid]) {
right = mid - 1;
} else if (target > nums[mid]) {
left = mid + 1;
} else {
return mid;
}
}
return left;
}
public int firstBadVersion(int n) {
int left = 1, right = n, mid;
while (left < right) {
// 如果left与right都超过了int最大值的1/2,那么(left+right)会发生溢出,
// 因此不能使用(left+right)/2求mid,而是应该用left+(right-left)/2
mid = left + ((right - left) >> 1);
if (isBadVersion(mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}