LeetCode997.找到小镇的法官

在一个小镇里,按从 1 到 N 标记了 N 个人。传言称,这些人中有一个是小镇上的秘密法官。

如果小镇的法官真的存在,那么:

小镇的法官不相信任何人。
每个人(除了小镇法官外)都信任小镇的法官。
只有一个人同时满足属性 1 和属性 2 。
给定数组 trust,该数组由信任对 trust[i] = [a, b] 组成,表示标记为 a 的人信任标记为 b 的人。

如果小镇存在秘密法官并且可以确定他的身份,请返回该法官的标记。否则,返回 -1。

示例 1:

输入:N = 2, trust = [[1,2]]
输出:2
示例 2:

输入:N = 3, trust = [[1,3],[2,3]]
输出:3
示例 3:

输入:N = 3, trust = [[1,3],[2,3],[3,1]]
输出:-1
示例 4:

输入:N = 3, trust = [[1,2],[2,3]]
输出:-1
示例 5:

输入:N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
输出:3

提示:

1 <= N <= 1000
trust.length <= 10000
trust[i] 是完全不同的
trust[i][0] != trust[i][1]
1 <= trust[i][0], trust[i][1] <= N

连接成邻接表依次查看出度和入度即可。

struct graphNode
{
    int label;
    std::vector<graphNode *> neighbors;
    graphNode(int x) : label(x) {};
};




class Solution {
public:
    int findJudge(int N, vector<pair<int,int>>& trust)
    {
        vector<graphNode*> graph;
        vector<int> out_degree;//出度为0,且入度为N-1的即为法官
        vector<int> in_degree;
        for(int i = 0; i <= N; ++i)
        {
            graph.emplace_back(new graphNode(i));
            out_degree.emplace_back(0);//初始出度都为0
            in_degree.emplace_back(0);
        }

        for(int i = 0; i < trust.size(); ++i)
        {
            graphNode* first = graph[trust[i].first];
            graphNode* second = graph[trust[i].second];
            first->neighbors.emplace_back(second);
            ++out_degree[first->label];//出度+1
            ++in_degree[second->label];
        }

        for(int i = 1; i < out_degree.size(); ++i)
        {
            if(out_degree[i] == 0 && in_degree[i] == N-1)
            {
                return i;
            }
        }
        return -1;
    }
};

题目链接:
https://leetcode-cn.com/problems/find-the-town-judge/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值