-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path277-Find_the_Celebrity.py
48 lines (38 loc) · 1.21 KB
/
277-Find_the_Celebrity.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# The knows API is already defined for you.
# return a bool, whether a knows b
# def knows(a: int, b: int) -> bool:
class SolutionII:
@lru_cache(maxsize=None)
def cachedKnows(self, a, b):
return knows(a, b)
def findCelebrity(self, n: int) -> int:
candidate = 0
for i in range(1, n):
if self.cachedKnows(candidate, i):
candidate = i
temp = True
for j in range(n):
if candidate == j: continue
if self.cachedKnows(candidate,j) or not self.cachedKnows(j,candidate):
temp = False
break
if temp:
return candidate
return -1
# Time Complexity : O(n)
Space Complexity : O(1)
class Solution:
def findCelebrity(self, n: int) -> int:
candidate = 0
for i in range(1, n):
if knows(candidate, i):
candidate = i
temp = True
for j in range(n):
if candidate == j: continue
if knows(candidate,j) or not knows(j,candidate):
temp = False
break
if temp:
return candidate
return -1