Practice Problem
- Stack
- Two Pointer
Eliminate non-celebrities in pairs, then verify the remaining candidate against all people.
O(n)
O(1)
class Solution {
private boolean knows(int a, int b) {
return true;
}
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 (i == candidate) continue;
if (knows(candidate, i) || !knows(i, candidate)) return -1;
}
return candidate;
}
}