277. Find the Celebrity

本文介绍了一个寻找名人问题的高效算法实现。该问题定义为在一个聚会中找到唯一一位被所有人认识但自己却不认识任何人的名人。通过两次遍历,首先确定候选人,再验证其是否为真正的名人,以此减少询问次数。

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.

 

这一题的关键在于选择candidate。假设选出的candiate = 10, 那么candidate对于10之后的所有人都不认识。显然真正的名人不可能在10之前,因为如果那样的话,candiate会停在名人的位置,不会走到10来。而且名人也不可能在10后面,因为如果那样的话,在第一个for循环时,candidate会停在名人的位置,而不是停在10。接下来检查candidate是不是名人,对于一个非candidate的人,如果candidate认识他或者他不认识candidate的话,那么这个candidate就不是名人。也就是说group里面名人不存在。

 1 class Solution(object):
 2     def findCelebrity(self, n):
 3         """
 4         :type n: int
 5         :rtype: int
 6         """
 7         candidate = 0
 8         for i in range(1,n):
 9             if knows(candidate, i):
10                 candidate = i
11         
12         for i in range(n):
13             if i != candidate and (knows(candidate, i) or not knows(i, candidate)):
14                 return -1
15         return candidate

 

转载于:https://www.cnblogs.com/lettuan/p/6847907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值