# The knows API is already defined for you.
# return a bool, whether a knows b
# def knows(a: int, b: int) -> bool:
class Solution:
def findCelebrity(self, n: int) -> int:
q = []
# 所有人入队
for i in range(n):
q.append(i)
while len(q) >= 2:
cand = q.pop()
other = q.pop()
if knows(cand, other) or not knows(other, cand):
# cand不可能是名人,让other归队
q.append(other)
else:
# other不可能是名人,让cand归队
q.append(cand)
# 只剩最后一个候选人,判断其是否为名人
cand = q.pop()
for i in range(n):
if i == cand: #跳过自身
continue
# 即看是否全部人都认识他,且他不认识任何人。有一个反面则-1
if not (knows(i, cand) and not knows(cand, i)):
return -1
return cand
class Solution:
def findCelebrity(self, n: int) -> int:
# 先假设cand是名人
cand = 0
other = 1
while other < n:
if knows(cand, other) or not knows(other, cand):
# cand不可能是名人,排除
# 假设other是名人
cand = other
# else:
# other 不可能是名人,排除
# 什么都不用做,继续假设 cand 是名人
other += 1
# 只剩最后一个候选人,判断其是否为名人
for i in range(n):
if i == cand: #跳过自身
continue
# 即看是否全部人都认识他,且他不认识任何人。有一个反面则-1
if not (knows(i, cand) and not knows(cand, i)):
return -1
return cand
class Solution:
def findCelebrity(self, n: int) -> int:
inDeg = [0] * n # 所有节点入度
outDeg = [0] * n # 所有节点出度
for i in range(n):
for j in range(i):
if knows(i, j):
outDeg[i] += 1
inDeg[j] += 1
if knows(j, i):
outDeg[j] += 1
inDeg[i] += 1
for k in range(n):
if inDeg[k] == n-1 and outDeg[k] == 0:
return k
return -1