Leetcode PHP題解--D106 997. Find the Town Judge
阿新 • • 發佈:2019-07-19
D106 997. Find the Town Judge
題目連結
題目分析
給定一個數組N代表人數,和給定一個數組,每個元素為一個只有兩個值(a,b)
的陣列。
代表a信任b。
從中找到一個b,b不信任任何人,但所有a都信任的b。我們稱它為法官。
思路
也即任何a是不能成為法官的。信任法官的人數需要等於N-1。
用array_column獲取a和b的陣列取名A和B。拿A和range(1,N)算差集,作為候選法官。
在用array_count_values計算陣列B中被信任的人的個數。
逐個遍歷候選法官,判斷被信任次數是否等於N-1。
最終程式碼
<?php class Solution { /** * @param Integer $N * @param Integer[][] $trust * @return Integer */ function findJudge($N, $trust) { $people = range(1, $N); $whoTrust = array_column($trust, 0); $beenTrusted = array_column($trust, 1); $possibleJudge = array_diff($people, $whoTrust); $trustedAmount = array_count_values($beenTrusted); foreach($possibleJudge as $p){ if($trustedAmount[$p] == ($N-1)){ return $p; } } return -1; } }