Sharing my 248ms C++ solution


  • 0
    T
    // Forward declaration of the knows API.
    bool knows(int a, int b);
    
    class Solution {
    public:
        int findCelebrity(int n) {
            if(n<=1)
                return 0;
                
            int celebrity=0;
            int i;
            for(i=1; i<n; i++)
                if(!knows(i, celebrity))
                    celebrity = i;
                    
            for(i=0; i<n; i++)
            {
                if(i!=celebrity && ( !knows(i, celebrity) || knows(celebrity, i) ))
                    return -1;
            }
            
            return celebrity;
        }
    };

Log in to reply
 

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