LeetCode 997. 找到小镇的法官

题目链接:

力扣icon-default.png?t=LA92https://leetcode-cn.com/problems/find-the-town-judge/

【分析】其实这是一道判断节点入度出度的简单题,但是我给想复杂了。法官只是入度为n-1,出度为0的节点而已。

class Solution {
    public int findJudge(int n, int[][] trust) {
        int[] in = new int[n + 1], out = new int[n + 1];
        int i, res = -1;
        for(i = 0; i < trust.length; i++){
            in[trust[i][1]]++;
            out[trust[i][0]]++;
        }
        for(i = 1; i <= n; i++){
            if(in[i] == n - 1 && out[i] == 0)
                res = i;
        }
        return res;
    }
}

 【笨办法】再来看看我用的笨方法,首先统计每个节点是否出现在左侧,然后以有点节点为键,将左边节点加入到一个set中,然后挨个判断set中元素的个数。

import java.util.*;

public class Solution {
    public int findJudge(int n, int[][] trust) {
        if(n == 1 && trust.length == 0) return 1;
        int[] cnt = new int[n + 1];
        Map<Integer, Set<Integer>> map = new HashMap<>();
        int i, l = trust.length, a, b, key, val;
        for(i = 0; i < l; i++){
            a = trust[i][0];
            b = trust[i][1];
            cnt[a] = 1;
            if(map.containsKey(b)){
                map.get(b).add(a);
            }else{
                map.put(b, new HashSet<>());
                map.get(b).add(a);
            }
        }
        int res = -1;
        Iterator<Map.Entry<Integer, Set<Integer>>> it = map.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry<Integer, Set<Integer>> entry = it.next();
            key = entry.getKey();
            if(cnt[key] == 1) continue;
            val = entry.getValue().size();
            if(val == n - 1){
                res = key;
                break;
            }
        }
        return res;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值