Problem 277

Posted by Ruizhi Ma on November 1, 2020

Solution URL

https://leetcode.com/submissions/detail/415675011/

代码

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

public class Solution extends Relation {
    //ans: Solution
    //Time: O(n^2)
    //Space: O(n)
    private int number;

    public int findCelebrity(int n) {
        number = n;
        //loop everyone to invocate isCelebrity func
        for(int i = 0; i < number; i++){
            if(isCelebrity(i)){
                return i;
            }
        }
        return -1;
    }

    public boolean isCelebrity(int i){
        for(int j = 0; j < number; j++){
            //dont ask themselvew
            if(j == i) continue;

            //if he knows others or other dont know him, not a celebrity
            if(knows(i, j) || !knows(j ,i)){
                return false;
            }
        }

        return true;
    }
}