408算法题leetcode--第21天

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. 找到小镇的法官

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;
    }
};
相关推荐
石去皿31 分钟前
力扣hot100 91-100记录
算法·leetcode·职场和发展
圣保罗的大教堂2 小时前
leetcode 2799. 统计完全子数组的数目 中等
leetcode
SsummerC2 小时前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
YuCaiH2 小时前
数组理论基础
笔记·leetcode·c·数组
2301_807611493 小时前
77. 组合
c++·算法·leetcode·深度优先·回溯
SsummerC4 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划
好易学·数据结构5 小时前
可视化图解算法:二叉树的最大深度(高度)
数据结构·算法·二叉树·最大高度·最大深度·二叉树高度·二叉树深度
程序员-King.5 小时前
day47—双指针-平方数之和(LeetCode-633)
算法·leetcode
阳洞洞5 小时前
leetcode 1035. Uncrossed Lines
算法·leetcode·动态规划·子序列问题
小鹿鹿啊6 小时前
C语言编程--15.四数之和
c语言·数据结构·算法