精華區beta Marginalman 關於我們 聯絡資訊
997. Find the Town Judge 一個小鎮中有n個人,每個人被1~n所編號,有個謠言說小鎮裡的一個人是法官,法官 滿足下列條件: 1.所有居民都信任法官 2.法官不相信任何人 給予一個陣列trust[][],trust[ai][bi]表示ai相信bi,找出小鎮裡的法官編號,若不 存在則返回-1。 Constraints: 1. ai != bi 2. All the pairs of trust are unique. 思路: 1. 用一個陣列儲存每個人的信用分數,如果他被一個人相信就+1,相信其他人就-1, 遍歷一次trust算出所有人的信用分數。 2.檢查所有人的信用分數,如果信用分數剛好等於 n-1 表示所有人都相信他且他不相 信其他人,若檢查完不存在就返回-1。 Java Code: ------------------------------------------- class Solution { public int findJudge(int n, int[][] trust) { int[] score = new int[n + 1]; for (int[] person : trust){ score[person[0]]--; score[person[1]]++; } for (int i = 1; i < score.length; i++){ if (score[i] == n - 1) { return i; } } return -1; } } ------------------------------------------- https://i.imgur.com/LYQh1ej.jpg -- https://i.imgur.com/sjdGOE3.jpg -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1674476912.A.2F9.html
Che31128: 大師 初二還在刷:0 01/23 20:30
sustainer123: 大師 01/23 20:33
DDFox: 大師 01/23 20:39
surimodo: 不要刷ㄌ 咕咕魯都要裁員了 01/23 20:40
pandix: 大師 01/23 21:00
SecondRun: 大師 01/23 21:01