二状态的二分搜索
在刷Leetcode中,常常见到一个序列,被切分为处于不同状态 s 1 s_1 s1和 s 2 s_2 s2的两个部分,例如 [ s 1 , s 1 , s 1 . . . s 2 , s 2 , s 2 ] [s_1,s_1,s_1...s_2,s_2,s_2] [s1,s1,s1...s2,s2,s2],要求找到 s 1 s_1 s1和 s 2 s_2 s2切分点。这里记录一下。可以利用如下模板进行解题。
// left和right分别为列表的左边界和右边界
int left = 0, right = nums.length - 1;
// 注意这里是小于而不是小于等于
while (left < right) {
int mid = left + ((right - left) >> 1);
// check(mid)为真表示满足前一种状态
if (check(mid)) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
例如这一题
剑指 Offer 53 - II. 0~n-1中缺失的数字
这里的序列被缺失的数字切分为两段,左段满足 n u m s [ i ] = i nums[i] = i nums[i]=i,而右端则 n u m s [ i ] ≠ i nums[i] \neq i nums[i]=i。用二分法搜索出切分点。
class Solution {
public int missingNumber(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] == mid) {
left = mid + 1;
} else {
right = mid;
}
}
// 考虑特殊情况,即末端缺失,例如[1];
return nums[left] == left ? left + 1 : left;
}
}
又例如这一题
278. 第一个错误的版本
这里以第一个错误版本为边界,将版本列表切分为[正确版本,错误版本]
,也可以如此搜索
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int left = 1, right = n;
while (left < right) {
int mid = left + ((right - left) >> 1);
if (isBadVersion(mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
旋转数组的二分搜索
经常看到要求旋转一个数组,求其最小值。或者利用最小值完成下一步操作。其模板如下。
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left >> 1);
if (nums[mid] > nums[left]) {
left = mid;
} else if (nums[mid] < nums[left]){
right = mid - 1;
} else {
left++;
}
}
return left;
剑指 Offer 11. 旋转数组的最小数字
剑指 Offer 11. 旋转数组的最小数字
这里无论有没有重复元素都会搜索到最小值。但是并不能定位到旋转数组的分割点。
class Solution {
public int minArray(int[] numbers) {
int left = 0, right = numbers.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (numbers[mid] < numbers[right]) {
right = mid;
} else if (numbers[mid] > numbers[right]) {
left = mid + 1;
} else {
right--;
}
}
return numbers[left];
}
}
33. 搜索旋转排序数组
33. 搜索旋转排序数组
当数组有重复元素,切割后
class Solution {
public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left >> 1);
if (nums[mid] > nums[right]) {
left = mid + 1;
} else if (nums[mid] < nums[right]){
right = mid;
} else {
right--;
}
}
int res1 = binarySearch(0, left - 1, nums, target);
if (res1 != -1)
return res1;
int res2 = binarySearch(left, nums.length - 1, nums, target);
if (res2 != -1)
return res2;
return -1;
}
int binarySearch(int left, int right, int[] nums, int target) {
while (left <= right) {
int mid = left + (right - left >> 1);
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
}