277. Find the Celebrity
Suppose you are at a party with
npeople (labeled from
n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other
n - 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 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
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
- O(3n): Explanation from scy_usc in here
- :The first loop will stop to an candidate i who doesn't know anyone from i+1 to n-1. For any previous x<i either know sb else or is not known by sb else.
- The second loop will check whether i knows anyone from 0 to i-1.
- The third loop is gonna check whether all party participants know x or not.
- O(2n): Explanation from czonzhu in here
- The first pass is to pick out the candidate. If candidate knows i, then switch candidate.
- The second pass is to check whether the candidate is real.
# 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 """ ix = 0 # check if someone knows ix and ix does not know anyone from ix + 1 to n -1 for i in range(n): if knows(ix, i): ix = i if any(knows(ix, i) for i in range(ix)): return -1 # check if ix knows any one from 0 to ix -1 if any(not knows(i, ix) for i in range(n)): return -1 # check if everyone else knows ix return ix