原题说明
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:
- The town judge trusts nobody.
- Everybody (except for the town judge) trusts the town judge.
- There is exactly one person that satisfies properties 1 and 2.
You are given trust, an array of pairstrust[i] = [a, b]
representing that the person labelled a trusts the person labelledb
.
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 <= N <= 1000
trust.length <= 10000
trust[i]
are all differenttrust[i][0] != trust[i][1]
1 <= trust[i][0], trust[i][1] <= N
解题思路
这是一道单向图的题,实际上我们要寻找图中入度为N-1
,出度为0
的点。
因为每个点的入度最大即为N-1
(即村上所有其他人都trust
他),所以入度 - 出度 = N - 1
是入度为N-1
,出度为0
的充分必要条件,所以本题用一个counts
数组统计每个点入度和出度之差,遍历trust
来更新counts
数组,之后再遍历counts
数组寻找值为N-1
的点,返回坐标即可,如果在counts
中不存在值为N-1
的点,说明不存在judge,返回-1
。
示例代码 (cpp)
1 | class Solution { |
复杂度分析
时间复杂度: O(T + N)
, T
为trust
数组的长度
空间复杂度: O(N)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!