C++ Solution (Should be Easy to understand)


  • 1
    Y
    // Forward declaration of the knows API.
    bool knows(int a, int b);
    
    class Solution {
    public:
        int findCelebrity(int n) {
            int ans = -1;
            if(n == 0)
                return ans;
            vector<int> knowed_cnt(n), know_cnt(n);
            for(int i = 0; i < n; ++ i){
                if(know_cnt[i] != 0)
                    continue;
                for(int j = 0; j < n; ++ j){
                if(i != j && knows(j, i)){
                        ++ knowed_cnt[i];
                        ++ know_cnt[j];
                    }
                }
                if(knowed_cnt[i] == n - 1){
                    bool isceleb = true;
                    for(int j = 0; j < n; ++ j){
                        if(i != j && knows(i, j)){
                            isceleb = false;
                            break;
                        }
                    }
                    if(isceleb){
                       ans = i;
                       break;
                    }
                }
            }
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.