LeetCode Binary Search Summary
二分搜索法小结
class Solution {
public:
int mySqrt(int x) {
if (x <= 1) return x;
int left = 0, right = x;
while (left < right) {
int mid = left + (right - left) / 2;
if (x / mid >= mid) left = mid + 1;
else right = mid;
}
return right - 1;
}
};
2、大于给定元素的最小元素
T744. Find Smallest Letter Greater Than Target (Easy)
class Solution {
public:
char nextGreatestLetter(vector<char>& letters, char target) {
if (target >= letters.back()) return letters[0];
int n = letters.size(), left = 0, right = n;
while (left < right) {
int mid = left + (right - left) / 2;
if (letters[mid] <= target) left = mid + 1;
else right = mid;
}
return letters[right];
}
};
3、有序数组的 Single Element
T540. Single Element in a Sorted Array (Medium)
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int left = 0, right = nums.size() - 1, n = nums.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] == nums[mid + 1]) {
if ((n - 1 - mid) % 2 == 1) right = mid;
else left = mid + 1;
} else {
if (mid == 0 || nums[mid] != nums[mid - 1]) return nums[mid];
if ((n - 1 - mid) % 2 == 0) right = mid;
else left = mid + 1;
}
}
return nums[left];
}
};
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
//int n = mid ^ 1;
//int n = m % 2 == 0 ? m + 1 : m - 1;
if (nums[mid] == nums[mid ^ 1]) left = mid + 1;
else right = mid;
}
return nums[left];
}
};
4、第一个错误的版本
T278. First Bad Version (Easy)
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int left = 1, right = n;
while (left < right) {
int mid = left + (right - left) / 2;
if (isBadVersion(mid)) right = mid;
else left = mid + 1;
}
return left;
}
};
5、旋转数组的最小数字
T153. Find Minimum in Rotated Sorted Array (Medium)
class Solution {
public:
int findMin(vector<int>& nums) {
int left = 0, right = (int)nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[right]) left = mid + 1;
else right = mid;
}
return nums[right];
}
};
6、查找区间
T34. Find First and Last Position of Element in Sorted Array
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int idx = search(nums, 0, nums.size() - 1, target);
if (idx == -1) return {-1, -1};
int left = idx, right = idx;
while (left > 0 && nums[left - 1] == nums[idx]) --left;
while (right < nums.size() - 1 && nums[right + 1] == nums[idx]) ++right;
return {left, right};
}
int search(vector<int>& nums, int left, int right, int target) {
if (left > right) return -1;
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target) return search(nums, mid + 1, right, target);
else return search(nums, left, mid - 1, target);
}
};