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;
    }
};
相关推荐
晚风(●•σ )1 分钟前
C++语言程序设计——12 排序算法-桶排序
c++·算法·排序算法
kgduu1 分钟前
Gin源码解析
算法·gin
小尧嵌入式18 分钟前
C++11线程库的使用(上)
c语言·开发语言·c++·qt·算法
蓝色汪洋26 分钟前
luogu填坑
开发语言·c++·算法
小年糕是糕手40 分钟前
【C++同步练习】类和对象(三)
开发语言·jvm·c++·程序人生·考研·算法·改行学it
CS创新实验室42 分钟前
计算机考研408【计算机网络】核心知识点总结
网络·计算机网络·考研·408
Learner__Q42 分钟前
每天五分钟:leetcode动态规划-递归与递推_day2
算法·深度优先
代码游侠1 小时前
学习笔记——Linux内核链表
linux·运维·笔记·学习·算法·链表
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2025.12.14 题目:2147.分隔长廊的方案数
linux·笔记·leetcode
发疯幼稚鬼1 小时前
插入排序与冒泡排序
c语言·数据结构·算法·排序算法