作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/rotting-oranges/

题目描述

In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.

If the town judge exists, then:

  1. The town judge trusts nobody.
  2. Everybody (except for the town judge) trusts the town judge.
  3. There is exactly one person that satisfies properties 1 and 2.

You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.

If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.

Example 1:

Input: N = 2, trust = [[1,2]]
Output: 2

Example 2:

Input: N = 3, trust = [[1,3],[2,3]]
Output: 3

Example 3:

Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1

Example 4:

Input: N = 3, trust = [[1,2],[2,3]]
Output: -1

Example 5:

Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3

Note:

  1. 1 <= N <= 1000
  2. trust.length <= 10000
  3. trust[i] are all different
  4. trust[i][0] != trusti
  5. 1 <= trust[i][0], trusti <= N

题目大意

镇里有编号1~N的N个人,如果有个法官存在的话,需要满足三个条件:

  1. 法官谁也不信任
  2. 每个人都信任这个人
  3. 只有一个人满足条件1和2

给出的trust[i] = [a, b]代表了a信任b。

如果法官存在,返回他的序号,否则返回-1.

解题方法

其实这个就是有向图,[a, b]表示从顶点a出发指向顶点b的一条有向边。

所以,题目的意思就是:是否存在且只存在一个顶点,所有的顶点都指向他,但是这个点不指向任何点。用术语来说就是该顶点的入度是N - 1,出度是0.

我们可以使用一个数组存储每个点的入度和出度的差,当某个点的入度和出度的差是N - 1时,代表他是法官,否则不存在。

证明:如果入度和出度的差 = N - 1,又入度、出度 >= 0,那么入度 = N- 1,出度 = 0,满足条件1和2.一旦存在一个点满足条件,那么说明这个点没有出度,所以不存在另一个点的入度是N - 1,满足条件3.

C++代码如下:

class Solution {
public:
int findJudge(int N, vector<vector<int>>& trust) {
vector<int> g(N + 1, 0); // in-degree - out-degree
for (auto t : trust) {
++g[t[1]];
--g[t[0]];
}
for (int i = 1; i <= N; ++i) {
if (g[i] == N - 1)
return i;
}
return -1;
}
};

日期

2019 年 2 月 24 日 —— 周末又结束了

最新文章

  1. 关于vue.js 组件的调用
  2. Eclipse中新建WEB项目,JSP页面报错。
  3. Python标准库11 多进程探索 (multiprocessing包)
  4. php中var_export与var_dump的区别分析
  5. 转载:SQL Server高效 -- 设计(ITPUT 讨论汇总
  6. cocos2d-x游戏开发系列教程-超级玛丽05-CMMenuScene
  7. 祖国版Solowheel!IPS103 独轮思维车 - 三个月体验报告
  8. sql 中获取最后生成的标识值 IDENT_CURRENT ,@@IDENTITY ,SCOPE_IDENTITY 的用法和区别
  9. NYOJ-914 Youth的最大化(贪心)
  10. Git 操作标签的一些命令
  11. [深度应用]&#183;首届中国心电智能大赛初赛开源Baseline(基于Keras val_acc: 0.88)
  12. 关于条件语句和 a &amp;&amp; b
  13. JGUI源码:Accordion鼠标中键滚动和手机端滑动实现(2)
  14. python中类似三元表达式的写法
  15. CentOS7下使用YUM安装MySQL5.6
  16. (27)session(设置值、取值、修改、删除)
  17. centos 6.8 配置csh的shell和环境变量
  18. [转载] 什么是istio 官网内容
  19. 【NOI2013】向量内积
  20. Java集合的ConcurrentModificationException

热门文章

  1. pycharm两个交互模式
  2. 利用elliipse做相关图
  3. C++类虚函数内存分布(这个 你必须懂)
  4. 解决CentOS7 docker容器映射端口只监听ipv6的问题
  5. 学习java 7.15
  6. vue-baidu-map相关随笔
  7. acclaim
  8. A Child&#39;s History of England.41
  9. redis入门到精通系列(五):redis的持久化操作(RDB、AOF)
  10. maven常用命令(待补充)