标签:for循环 rom oss pos pre imp ret 这一 who
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
标签:for循环 rom oss pos pre imp ret 这一 who
原文地址:http://www.cnblogs.com/lettuan/p/6847907.html