[leetcode] 277. Find the Celebrity @ python

原题

https://leetcode.com/problems/find-the-celebrity/

解法

首先遍历n个人, 找出可能的候选人cand, 根据名人的定义, 名人是所有人都认识他, 但他不认识别人. 所以, 当knowns(cand, i)为真时, cand需要更新为i, 根据题意, n个人中最多有一个名人, 那么遍历完之后的这个cand就是候选人. 再遍历n个人, 根据定义确定cand是否为名人.

Time: O(2*n)
Space: O(1)

代码

# The knows API is already defined for you.
# @param a, person a
# @param b, person b
# @return a boolean, whether a knows b
# def knows(a, b):

class Solution(object):
    def findCelebrity(self, n):
        """
        :type n: int
        :rtype: int
        """
        cand = 0
        for i in range(1, n):
            if knows(cand, i):
                cand = i
                
        for i in range(n):
            if i != cand and (not knows(i, cand) or knows(cand, i)):
                return -1
        return cand

你可能感兴趣的:(Leetcode)