[简单] 997. 找到小镇的法官
https://leetcode-cn.com/problems/find-the-town-judge/
我只会写一些垃圾代码:
class Solution { public int findJudge(int n, int[][] trust) { class NodeMap { int resident; // 小镇居民 int truster; // 小镇居民信任的人. public int getResident() { return resident; } public void setResident(int resident) { this.resident = resident; } public int getTruster() { return truster; } public void setTruster(int truster) { this.truster = truster; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NodeMap nodeMap = (NodeMap) o; return resident == nodeMap.resident && truster == nodeMap.truster; } @Override public int hashCode() { return Objects.hash(resident, truster); } public NodeMap(int resident, int truster) { this.resident = resident; this.truster = truster; } } int ret = -1; if((trust == null || trust.length == 0)) { if(n == 1) return 1; else return -1; } if (trust.length == 1) { ret = trust[0][1]; } else { // 获取信任映射关系 List<NodeMap> allTrustMap = new ArrayList<>(); Set<Integer> setResident = new HashSet<>(); // 居民列表 for (int m = 0; m < trust.length; m++) { allTrustMap.add(new NodeMap(trust[m][0], trust[m][1])); setResident.add(trust[m][0]); setResident.add(trust[m][1]); } int iResidentCount = setResident.size(); List<Integer> st = new ArrayList<>();// 获取不相信任何人的列表. for (int i = 1; i <= n; i++) { boolean bNoTruster = false; for (NodeMap node : allTrustMap) { if(node.getResident() == i) { bNoTruster = true; } } if(!bNoTruster) { st.add(i); } } // 检查不信任任何人的列表是否均被所有人新人, 若是则判断为法官. for (int m = 0; m < st.size(); m++) { int u = st.get(m);// 当前可能是法官的人. Set<Integer> setTruster = new HashSet<>(); for(int k = 1; k <= n; k++) { // 遍历小镇居民 if(k == u) continue; // 屏蔽掉当前怀疑是发官的对象. for(NodeMap e : allTrustMap) { int curResident = e.getResident(); int curTruster = e.getTruster(); if(k == curResident && u == curTruster) { setTruster.add(k); continue; } } } if (setTruster.size() >= (iResidentCount - 1)) { ret = u; break; } } } return ret; } }