Problem:
Analysis:
method1:
first of all, we can use the array with 2 dimensions to check each pair, which time complexity will be O(n^2)
method2:
- the first pass for all the people, find the celebrity candidate who doesn’t know anyone.
- if (knows(A, B)):
* A is not Celebrity; - else:
* B is not Celebrity }
- the second pass, to make sure that the candidate is indeed the celebrity, or return -1;
/**
*
* @author shaohua
*boolean knows(A, B)
*
* 1. find the celebrity candidate who doesn't know the person behind him
* 2. make sure candidate is celebrity
*
*/
public class Solution1 {
public int findCelebrity(int n) {
int candidate = 0;
for (int i=1; i<n; i++) {
if (knows(candidate, i)) {
candidate = i;
}
}
for(int i=0; i<n; i++) {
if (candidate == i) {
continue;
}
if (knows(candidate,i) || !knows(i,candidate)) {
return -1;
}
}
return candidate;
}
}