(图论基础题) leetcode 997. Find the Town Judge
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 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 <= N <= 1000
trust.length <= 10000
trust[i]
are all differenttrust[i][0] != trust[i][1]
1 <= trust[i][0], trust[i][1] <= N
==================================================================
PS:记得几个月前在leetcode周赛上做这个题时,当时没有好好学图论,觉得这个题怎么这么难,还是但是标签是easy。。。最后用了一个很麻烦的方法写了。现在,学了图论后,发现这个题是真的很easy。。。看来,我还需要更加努力了
这个题是图论题,就是找入度为N-1和出度为0的点,trust他人就是出度,被trust就是入度。所以,最后这个题可以化为入度和出度差值为N-1的人。没找到就返回-1。
C++代码:
class Solution { public: int findJudge(int N, vector<vector<int>>& trust) { vector<int> vec(N+1,0); for(auto t : trust){ vec[t[0]]--; vec[t[1]]++; } for(int i = 1; i <= N; i++){ if(vec[i] == N-1) return i; } return -1; } };
另外附上几个月前写的代码:
class Solution { public: int findJudge(int N, vector<vector<int>>& trust) { set<int> s1,s2; if(trust.size() == 0) return 1; int num; vector<vector<int> > ans; for(int i = 0; i < trust.size(); i++){ s1.insert(trust[i][0]); s2.insert(trust[i][1]); } for(set<int>::iterator it = s2.begin(); it!=s2.end(); it++){ if(s1.count(*it)) s2.erase(*it); } if(s2.size() != 1) return -1; else{ for(set<int>::iterator it = s2.begin(); it!=s2.end(); it++){ num = *it; } for(int i = 0;i < trust.size(); i++){ if(trust[i][1] == num){ ans.push_back(trust[i]); } } if(ans.size() == N - 1) return ans[0][1]; else return -1; } } };