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;
    }
};
相关推荐
Hygge-star18 分钟前
【数据结构】二分查找5.12
java·数据结构·程序人生·算法·学习方法
June`2 小时前
专题二:二叉树的深度搜索(二叉树剪枝)
c++·算法·深度优先·剪枝
黄暄2 小时前
初识计算机网络。计算机网络基本概念,分类,性能指标
笔记·学习·计算机网络·考研
好吃的肘子3 小时前
Elasticsearch架构原理
开发语言·算法·elasticsearch·架构·jenkins
胡耀超3 小时前
霍夫圆变换全面解析(OpenCV)
人工智能·python·opencv·算法·计算机视觉·数据挖掘·数据安全
软行3 小时前
LeetCode 每日一题 3341. 到达最后一个房间的最少时间 I + II
数据结构·c++·算法·leetcode·职场和发展
nlog3n3 小时前
Go语言交替打印问题及多种实现方法
开发语言·算法·golang
How_doyou_do3 小时前
备战菊厂笔试4
python·算法·leetcode
朱剑君3 小时前
第九天——贪心算法——非递减数组
算法·贪心算法
Wnq100724 小时前
工业场景轮式巡检机器人纯视觉识别导航的优势剖析与前景展望
人工智能·算法·计算机视觉·激光雷达·视觉导航·人形机器人·巡检机器人