LeetCode知识点总结 - 997
LeetCode 997. Find the Town Judge
| Hash Table | Easy |
題目
In a town, there are n people labeled 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 an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.
Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.
思路
用一個array儲存所有人被trust - trust的結果(trust別人-1,被trust+1),最后遍歷array找到值為n-1的位置。
答案
class Solution {public int findJudge(int n, int[][] trust) {if(trust.length == 0){return n == 1 ? 1 : -1;}int[] trustCount = new int[n+1];for(int[] t : trust){trustCount[t[1]]++;trustCount[t[0]]--;}for(int i = 1; i < trustCount.length;i++){if(trustCount[i] == n-1)return i;}return -1;} }總結
以上是生活随笔為你收集整理的LeetCode知识点总结 - 997的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转载】论付出感
- 下一篇: 爱情来的太快就像龙卷风