669. 修剪二叉搜索树
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/15862f45c94986f3ba4bd1cfad5b2565.png)
代码实现(自解)
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (!root) return nullptr;
int val = root->val;
if (val < low) {
return trimBST(root->right, low, high);
}
if (val > high) {
return trimBST(root->left, low, high);
}
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};
547. 省份数量
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/60635505777c962c8182b73f47b31ee1.png)
代码实现(自解)
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
set<int> connected;
int count = 0;
queue<int> myQueue;
int n = isConnected.size();
for (int i = 0; i < n; i++) {
if (connected.count(i)) continue;
connected.emplace(i);
count++;
myQueue.push(i);
while (!myQueue.empty()) {
int tmp = myQueue.front();
myQueue.pop();
for (int j = 0; j < n; j++) {
if (isConnected[tmp][j] && !connected.count(j)) {
myQueue.push(j);
connected.emplace(j);
}
}
}
}
return count;
}
};
1319. 连通网络的操作次数
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/268604886eea6c85db83ee9d1f4f0d9a.png)
代码实现(自解)
class Solution {
private:
vector<int> parent;
public:
int myFind(int i) {
if (parent[i] != i) {
i = myFind(parent[i]);
}
return i;
}
void myUnion(int i, int j) {
parent[myFind(i)] = parent[myFind(j)];
}
int makeConnected(int n, vector<vector<int>>& connections) {
if (n - 1 > connections.size()) return -1;
parent = vector<int>(n);
for (int i = 0; i < n; i++) {
parent[i] = i;
}
for (auto arr : connections) {
myUnion(arr[0], arr[1]);
}
int count = -1;
for (int i = 0; i < n; i++) {
count += (parent[i] == i);
}
return count;
}
};
939. 最小面积矩形
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/99a29345d2b7677d09962e604e80fcb9.png)
代码实现(自解)
class Solution {
public:
int minAreaRect(vector<vector<int>>& points) {
int ans = INT_MAX;
map<int, set<int>> rowMap;
for (auto& arr : points) {
rowMap[arr[0]].emplace(arr[1]);
}
for (auto &[row, s] : rowMap) {
if (s.size() == 1) continue;
for (auto it = s.begin(); it != s.end(); it++) {
auto it2 = it;
int col1 = *it;
for (it2++; it2 != s.end(); it2++) {
int col2 = *it2;
for (auto &[row1, s1] : rowMap) {
if (row1 == row) continue;
if (s1.count(col1) && s1.count(col2)) {
ans = min(ans, abs((row1 - row) * (col2 - col1)));
}
}
}
}
}
return (ans == INT_MAX) ? 0 : ans;
}
};