題目
在一個(gè)小鎮(zhèn)里爷速,按從 1 到 N 標(biāo)記了 N 個(gè)人陵刹。傳言稱,這些人中有一個(gè)是小鎮(zhèn)上的秘密法官切揭。
如果小鎮(zhèn)的法官真的存在狞甚,那么:
小鎮(zhèn)的法官不相信任何人。
每個(gè)人(除了小鎮(zhèn)法官外)都信任小鎮(zhèn)的法官廓旬。
只有一個(gè)人同時(shí)滿足屬性 1 和屬性 2 哼审。
給定數(shù)組 trust,該數(shù)組由信任對(duì) trust[i] = [a, b] 組成孕豹,表示標(biāo)記為 a 的人信任標(biāo)記為 b 的人涩盾。
如果小鎮(zhèn)存在秘密法官并且可以確定他的身份,請(qǐng)返回該法官的標(biāo)記励背。否則春霍,返回 -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
C++解法
class Solution {
public:
int findJudge(int N, vector<vector<int>>& trust) {
vector<int> trust_count(N, 0);
vector<int> trusted_count(N, 0);
for (auto item: trust) {
trust_count[item[0] - 1] ++;
trusted_count[item[1] - 1]++;
}
for (int i = 0; i < N; i++) {
if (trusted_count[i] == N - 1) {
if (trust_count[i] == 0) { return i + 1; }
else {return -1;}
}
}
return -1;
}
};
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-the-town-judge