forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfind-the-celebrity.py
More file actions
29 lines (28 loc) · 857 Bytes
/
find-the-celebrity.py
File metadata and controls
29 lines (28 loc) · 857 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Time: O(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
"""
candidate = 0
# Find the candidate.
for i in xrange(1, n):
if knows(candidate, i): # noqa
candidate = i # All candidates < i are not celebrity candidates.
# Verify the candidate.
for i in xrange(n):
candidate_knows_i = knows(candidate, i) # noqa
i_knows_candidate = knows(i, candidate) # noqa
if i != candidate and (candidate_knows_i or
not i_knows_candidate):
return -1
return candidate