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;
    }
};
相关推荐
纪元A梦9 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_9 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
mark-puls10 小时前
C语言打印爱心
c语言·开发语言·算法
Python技术极客10 小时前
将 Python 应用打包成 exe 软件,仅需一行代码搞定!
算法
吃着火锅x唱着歌10 小时前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun10 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌10 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
我星期八休息10 小时前
深入理解跳表(Skip List):原理、实现与应用
开发语言·数据结构·人工智能·python·算法·list
lingran__11 小时前
速通ACM省铜第四天 赋源码(G-C-D, Unlucky!)
c++·算法
haogexiaole11 小时前
贪心算法python
算法·贪心算法