*277. Find the Celebrity

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

solution

class Solution:
    def findCelebrity(self, n: int) -> int:
        candidate = 0
        for i in range(1, n):
            # If the candidate knows person i, then switch candidate to i
            if knows(candidate, i):
                candidate = i

        for i in range(n):
            if candidate != i:
                if knows(candidate, i) or not knows(i, candidate):
                    return -1
        return candidate

时间复杂度:O(n) 空间复杂度:O(1)

Last updated