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.
풀이
재미있는 문제이다.
마을에 판사가 존재한다면, 아래 조건을 만족한다.
- 마을의 모든 사람은 판사를 믿는다.
- 판사는 마을 사람을 아무도 믿지 않는다.
마을 사람간 신뢰 정보가 주어졌을 때, 판사가 존재하면 그 사람의 번호를, 존재하지 않는다면 -1을 정답으로 리턴하면 된다.
N명의 사람 중 판사가 존재한다면 판사 자신을 제외한 N-1명이 한 사람을 믿게 된다.
따라서 count 배열을 이용하여 확인하였고, 판사는 마을 사람을 아무도 믿지 않기 때문에 다시 한번 for문을 통해 확인해주었다.
코드
class Solution {
public int findJudge(int N, int[][] trust) {
if(N == 1)
return 1;
int []count = new int[N + 1];
int answer = -1;
for(int i=0;i<trust.length;i++){
count[trust[i][1]]++;
if(count[trust[i][1]] >= N - 1){
answer = trust[i][1];
break;
}
}
for(int i=0;i<trust.length;i++){
if(trust[i][0] == answer){
answer = -1;
break;
}
}
return answer;
}
}