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 - 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 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.
思路:
1. 简单粗暴的方法,需要两两判断,复杂度就是o(n^2)。这题肯定不是考察这么做。是否有更快的方法,应该根据条件:只有一个celebrity或者没有,是复杂度o(n)。参考https://discuss.leetcode.com/topic/23534/java-solution-two-pass/15 two pass的方法,第一次找candidate,第二次verify candidate是否是celebrity。
2. 思路是这样的,令candidate=0,然后判断knows(candidate,i):等于1,则candidate认识i,所以update candidate=i; 等于0,则不认识,可以继续i++; 能这么做的原因是:若k为candidate,则0~k-1不可能是celebrity,因为肯定认识至少一个人;k+1~n-1也不可能是celebrity,因为有至少一个人(candidate)不认识他。
3. 还可以继续思考,别人为什么能想到o(n)的方法?但是,至少根据要求,n个人,只有1个可能celebrity,类似这样条件,应该form a sense that the optimal time complexity is o(n)!
int findCelebrity(int n) {
//two pass
int candidate=0;
for(int i=0;i<n;i++){
if(knows(candidate,i)) candidate=i;
}
for(int i=0;i<n;i++){
//由于candidate后面的人和candidate,knows(candidate,i)肯定都为0,所以不同再判断!
if(i<candidate&&knows(candidate,i)) return -1;//candidate不认识前面的人,认识的话,就不是celebrity
if(i!=candidate&&!knows(i,candidate)) return -1;//i是否都认识candidate,有一个认识,就不是celebrity
}
return candidate;
}