Problem
Suppose you are at a party with
n
people (labeled from0
ton - 1
) and among them, there may exist one celebrity. The definition of a celebrity is that all the othern - 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 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
.
Solution
遍历每一个人,看其余的n-1
个人是否都认识这个人,如果是,那么如果这个人不认识任何人则输出,否则继续下一个人。
// Forward declaration of the knows API.
bool knows(int a, int b);
class Solution {
public:
int findCelebrity(int n) {
for(int i = 0; i < n; i++) {
bool flag = false;
for(int j = 0; j < n; j++) {
if (i != j && !knows(j, i)) {
flag = true;
break;
}
}
if (!flag) {
flag = false;
for(int j = 0; j < n; j++) {
if (i != j && knows(i, j)) {
flag = true;
break;
}
}
if (!flag) {
return i;
}
}
}
return -1;
}
};
优化
O(n).
以下是第一重循环的解释。
Let's say i = k, you first time switch candidate, then 0 ~ k -1 will not have candidate. 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. So if the pre candidate(0) doesn't know 1 ~ k-1, then 1 ~ k - 1 are not celebrity. As you just switch candidate, then 0 is not.
code
// Forward declaration of the knows API.
bool knows(int a, int b);
class Solution {
public:
int findCelebrity(int n) {
int candidate = 0;
// If candidate does not know k (0 ~ i-1). It means that k cannot be celebrity, since celebrity
// must be known by everyone.
for(int i = 1; i < n; i++) {
if (knows(candidate, i)) {
candidate = i;
}
}
for(int j = 0; j < n; j++) {
if (candidate != j && (knows(candidate, j) || !knows(j, candidate))) {
return -1;
}
}
return candidate;
}
};