文章目录
真正写对「二分查找」,从来不在于我们把区间写成了「左闭右开」还是「左闭右闭」,而是 在于我们能够根据题意:得到某种单调性,和可以逐步缩小搜索规模的条件,进而准确地设计可以使得搜索区间缩小的条件。
1252. 奇数值单元格的数目(140)
代码实现(首刷自解)
class Solution {
public:
int oddCells(int m, int n, vector<vector<int>>& indices) {
vector<bool> colAndRow(m + n, false);
for (int i = 0; i < indices.size(); i++) {
colAndRow[indices[i][0]] = !colAndRow[indices[i][0]];
colAndRow[m + indices[i][1]] = !colAndRow[m + indices[i][1]];
}
int cal = 0;
for (int i = m; i < n + m; i++) {
cal += (colAndRow[i] == true) ? 1 : 0;
}
int ans = 0;
for (int i = 0; i < m; i++) {
ans += colAndRow[i] ? (n - cal) : cal;
}
return ans;
}
};
287. 寻找重复数(141)
代码实现(首刷自解)
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int l = 1;
int n = nums.size();
int r = n - 1;
while (l < r) {
int m = ((l + r) >> 1);
int count = 0;
for (int num : nums) {
if (num <= m) count++;
}
if (count > m) r = m;
else l = m + 1;
}
return l;
}
};
35. 搜索插入位置(142)
代码实现(首刷自解)
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
if (target > nums[n - 1]) return n;
int l = 0, r = n - 1;
while (l < r) {
int m = (l + r) / 2;
if (nums[m] < target) l = m + 1;
else r = m;
}
return l;
}
};
69. x 的平方根(143)
代码实现(首刷自解)
class Solution {
public:
int mySqrt(int x) {
int l = 1, r = x;
while (l < r) {
int m = l + (r - l) / 2;
if (m <= x / m && m + 1 > x / (m + 1)) {
return m;
}
if (m > x / m) r = m - 1;
else l = m + 1;
}
return r;
}
};
1283. 使结果不超过阈值的最小除数(144)
代码实现(首刷自解)
class Solution {
public:
int smallestDivisor(vector<int>& nums, int threshold) {
int l = 1, r = *max_element(nums.begin(), nums.end());
while (l < r) {
int m = (l + r) / 2;
int count = 0;
for (int num : nums) {
count += num / m + (num % m > 0);
}
if (count <= threshold) r = m;
else l = m + 1;
}
return l;
}
};