Find the Celebrity
Problem: Find the Celebrity
First we need to find a potential celebrity by checking whether he knows anyone, then check whether he's known by everyone.
Code in Python:
class Solution(object):
def findCelebrity(self, n):
"""
:type n: int
:rtype: int
"""
x = 0
for i in xrange(1, n):
if knows(x, i): x = i
if any(knows(x, i) for i in xrange(x)):
return -1
if any(not knows(i, x) for i in xrange(n)):
return -1
return x
Basically, the first two iteration check whether he knows anyone. The last iteration checks whether he's known by everyone.s