边工作边刷题:70天一遍leetcode: day 85
Find the Celebrity
要点:
- 这题从solution反过来想比较好:loop through n同时maintain一个candidate:如果cand认识某个i,那么modify cand。实际上检查另一个条件i不认识cand也可以,因为这2个条件是exclusive的
- 这个过程保证了cand不认识其之后的所有人。两个问题:
- 一是会不会漏掉之前可能的celebrity呢?不会,如果当前cand不know i,i不可能是candidate。
- 因为只是确保了之后的所有人,会不会是False positive呢?所以要再loop确认结果。所以两个loop一个验证必要条件,一个验证充分条件
- 最后验证的时候要两个条件都验证,否则0 knows 1, 1 knows 0的情况会错
# Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them.
# Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).
# You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows.
# Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1.
# Hide Company Tags LinkedIn Facebook
# Hide Tags Array
# 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
"""
cand = 0
for i in xrange(1,n):
if knows(cand, i):
cand = i
for i in xrange(n):
if i!=cand:
if not knows(i,cand) or knows(cand, i):
return -1
return cand
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步