997. Find the Town Judge

题目

在这里插入图片描述

我的代码(效率低到令人发指)

class Solution(object):
    def findJudge(self, N, trust):
        """
        :type N: int
        :type trust: List[List[int]]
        :rtype: int
        """
        if N==1:
            return 1
        cnt=collections.Counter()
        for t in trust:
            cnt[t[1]]+=1
        sign=False
        result=None
        for k in cnt:
            if cnt[k]==N-1:
                if sign==True:
                    return -1
                else:
                    sign=True
                    result=k
        if result:
            for t in trust:
                if t[0]==result:
                    return -1 
            return result
        return -1      

优秀代码

class Solution(object):
    def findJudge(self, N, trust):
        """
        :type N: int
        :type trust: List[List[int]]
        :rtype: int
        """
        
        '''
        [1, ...., N]
        
        A trusts B
        C trusts B
        B trustees = [A, C]
        '''
        
        x = set(range(1, N+1))
        for (a, b) in trust:
            if a in x:
                x.remove(a)
        if len(x) != 1:
            return -1
        
        judge_cand = list(x)[0]
        cnt_trust = 0
        for (a, b) in trust:
            if b == judge_cand:
                cnt_trust += 1
        
        if cnt_trust == N-1:
            return judge_cand
        return -1

猜你喜欢

转载自blog.csdn.net/xiabenshu/article/details/88985466