真正写对「二分查找」,从来不在于我们把区间写成了「左闭右开」还是「左闭右闭」,而是 在于我们能够根据题意:得到某种单调性,和可以逐步缩小搜索规模的条件,进而准确地设计可以使得搜索区间缩小的条件。
558. 四叉树交集
代码实现(首刷自解)
/*
// Definition for a QuadTree node.
class Node {
public:
bool val;
bool isLeaf;
Node* topLeft;
Node* topRight;
Node* bottomLeft;
Node* bottomRight;
Node() {
val = false;
isLeaf = false;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
Node(bool _val, bool _isLeaf) {
val = _val;
isLeaf = _isLeaf;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
val = _val;
isLeaf = _isLeaf;
topLeft = _topLeft;
topRight = _topRight;
bottomLeft = _bottomLeft;
bottomRight = _bottomRight;
}
};
*/
class Solution {
public:
Node* intersect(Node* quadTree1, Node* quadTree2) {
if (quadTree1->isLeaf && quadTree2->isLeaf) {
return new Node(quadTree1->val | quadTree2->val, true);
}
if ((!quadTree1->isLeaf) && (!quadTree2->isLeaf)) {
Node* tmp = new Node(true, false, intersect(quadTree1->topLeft,
quadTree2->topLeft), intersect(quadTree1->topRight,
quadTree2->topRight), intersect(quadTree1->bottomLeft,
quadTree2->bottomLeft), intersect(quadTree1->bottomRight,
quadTree2->bottomRight));
if (tmp->topLeft->isLeaf && tmp->topRight->isLeaf &&
tmp->bottomLeft->isLeaf && tmp->bottomRight->isLeaf &&
tmp->bottomLeft->val == tmp->bottomRight->val &&
tmp->bottomLeft->val == tmp->topLeft->val &&
tmp->topLeft->val == tmp->topRight->val) {
return new Node(tmp->topLeft->val, true);
}
return tmp;
}
if (quadTree1->isLeaf) {
return quadTree1->val ? quadTree1 : quadTree2;
}
return quadTree2->val ? quadTree2 : quadTree1;
}
};
240. 搜索二维矩阵 II
代码实现(部分看题解)
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
int n = matrix[0].size();
int x = m - 1, y = 0;
while (x >= 0 && y < n) {
if (matrix[x][y] == target) return true;
if (matrix[x][y] < target) y++;
else x--;
}
return false;
}
};
274. H 指数
代码实现(首刷自解)
class Solution {
public:
int hIndex(vector<int>& citations) {
sort(citations.begin(), citations.end());
int l = 1, r = citations.size();
int n = r;
if (!citations.back()) return 0;
if (n == 1) return min(citations[0], 1);
int ans = 0;
while (l <= r) {
int m = (l + r) >> 1;
if (citations[n - m] >= m) {
l = m + 1;
if (n - m == 0 || citations[n - m - 1] <= m) {
ans = max(ans, m);
}
}
else {
r = m - 1;
}
}
return ans;
}
};
275. H 指数 II
代码实现(首刷自解)
class Solution {
public:
int hIndex(vector<int>& citations) {
int l = 1, r = citations.size();
int n = r;
if (!citations.back()) return 0;
if (n == 1) return min(citations[0], 1);
int ans = 0;
while (l <= r) {
int m = (l + r) >> 1;
if (citations[n - m] >= m) {
l = m + 1;
if (n - m == 0 || citations[n - m - 1] <= m) {
ans = max(ans, m);
}
}
else {
r = m - 1;
}
}
return ans;
}
};