74. 搜索二维矩阵
cpp
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
// 把矩阵转换为一维数组
// 一维id > 二维id / n, id % n
int m = matrix.size(), n = matrix[0].size();
int size = m * n;
int l = 0, r = size; // 左闭右开
while(l < r){
int mid = l + (r - l) / 2;
int x = matrix[mid / n][mid % n];
if(x >= target){
r = mid;
} else {
l = mid + 1;
}
}
if(l >= size) return false;
return matrix[l / n][l % n] == target;
}
};
997. 找到小镇的法官
- 997. 找到小镇的法官
- 思路:图的概念
- 时间:O(m+n);空间:O(n)
cpp
class Solution {
public:
int findJudge(int n, vector<vector<int>>& trust) {
// 找入度为n-1,且出度为0的点
vector<int>in(n+1, 0), out(n+1, 0);
for(auto it : trust){
int p = it[0], q = it[1]; // p > q
out[p]++, in[q]++;
}
// 遍历in和out
int ret = 0;
for(int i = 1; i <= n; i++){
if(in[i] == n - 1 && out[i] == 0){
return i;
}
}
return -1;
}
};
1557. 可以到达所有点的最少点数目
cpp
class Solution {
public:
vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
// 入度为0的点的集合,因为入度不为0的点一定可以由入度为0的点指向
vector<int>ret;
vector<int>in(n, 0);
for(auto it : edges){
in[it[1]]++;
}
for(int i = 0; i < n; i++){
if(in[i] == 0){
ret.push_back(i);
}
}
return ret;
}
};