Leetcode - Find the Town Judge 找到镇法官

285 阅读2分钟

In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.

If the town judge exists, then:

    1. The town judge trusts nobody.
    1. Everybody (except for the town judge) trusts the town judge.
    1. There is exactly one person that satisfies properties 1 and 2.

You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.

If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.

Note:

    1. 1 <= N <= 1000
    1. trust.length <= 10000
    1. trust[i] are all different
    1. trust[i][0] != trust[i][1]
    1. 1 <= trust[i][0], trust[i][1] <= N

就是在给定的二维数组中[x , y]表示 x 信任 y。镇法官不信任任何人。如果存在所有人都信任一个人,这个人不信任任何人,那么这个人就是镇法官。数组不会出现自己信任自己以及重复的情况。

解法1:因为 N <= 1000,所以可以使用存储所有的1-N为key,value为List的Map,碰到数组的a[0],则map删除a[0]键值,添加a[1]键值的list.add(a[0]).最后遍历map,所以list满足大小为N-1,则为结果,代码如下:

class Solution{
    public int findJudge(int N, int[][] trust) {
        Map<Integer,List<Integer>> map = new HashMap();
        for(int i=1; i<N+1; i++){
            map.put(i, new ArrayList());
        }
        
        for(int i=0; i<trust.length; i++){
            int key   = trust[i][0];
            int value = trust[i][1];
            
            map.remove(key);
            if(map.containsKey(value)){
                map.get(value).add(key);
            }
        }
        
        for(Map.Entry<Integer,List<Integer>> entry : map.entrySet()){
            if(entry.getValue().size() == N-1){
                return entry.getKey();
            }
        }
        return -1;
    }
}

解法2:使用一个数组,下标index表示第k个人,值表示(被多少人信任-信任的人数),所以最终如果满足 result[index] == N-1,则是镇法官。

class Solution {
    public int findJudge(int N, int[][] trust) {
        int[] result = new int[N+1];
        for(int i=0; i<trust.length; i++){
            //信任别人,自己的值-1
            result[trust[i][0]]--;
            //被别人信任,自己的值+1
            result[trust[i][1]]++;
        }
        
        //因为trust满足不会有重复值和自己信任自己的情况,所以result[i]最多为N-1
        for(int i=1; i<N+1; i++){
            if(result[i] == N-1){
                return i;
            }
        }
        return -1;
    }
}