277.搜寻名人
一、模拟
# 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改进
二、图(超时)
最后更新于