Suppose you are at a party withnpeople (labeled from0ton - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the othern - 1people 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 functionbool knows(a, b)which tells you whether A knows B. Implement a functionint findCelebrity(n), your function should minimize the number of calls toknows.
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.
For loops also have anelseclause which most of us are unfamiliar with. Theelseclause executes when the loop completes normally. This means that the loop did not encounter anybreak. They are really useful once you understand where to use them. I myself came to know about them a lot later.
The common construct is to run a loop and search for an item. If the item is found, we break the loop usingbreak. There are two scenarios in which the loop may end. The first one is when the item is found andbreakis encountered. The second scenario is that the loop ends. Now we may want to know which one of these is the reason for a loops completion. One method is to set a flag and then check it once the loop ends. Another is to use theelseclause.
两个for/else loop的例子:
for item in container:
if search_something(item):
# Found it!
process(item)
break
else:
# Didn't find anything..
not_found_in_container()
It finds factors for numbers between 2 to 10. Now for the fun part. We can add an additionalelseblock which catches the numbers which are prime and tells us so:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print( n, 'equals', x, '*', n/x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
# 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
"""
for i in xrange(n):
for j in xrange(n):
if i==j:
continue
if [knows(i,j), knows(j,i)] != [False, True]:
break
else:
return i
return -1