277. Find the Celebrity!

/* The knows API is defined in the parent class Relation.
      boolean knows(int a, int b); */

public class Solution extends Relation {
    public int findCelebrity(int n) {
        // 1. if there is a celebrity, the celebrity must be unique
        // 2. within a and b, one of them must not be celebrity
        // set 0 as the first possible candidate
        int candidate = 0;
        for(int other=1; other<n; other++){
            if(knows(other, candidate) && !knows(candidate, other)){
                // candidate is still a possible celebrity
                // and other must not be the celebrity
            }else{
                // set other as possible celebrity
                candidate=other;
            }
        }
        
        for(int other=0; other<n; other++){
            if(other==candidate) continue;
            if (!knows(other, candidate) || knows(candidate, other)){
                return -1;
            }
        }
        return candidate;
    }
}

Last updated