MS 645. Find the Celebrity

Code(Language:C++) (Judger:ip-172-31-21-252)
// Forward declaration of the knows API.
bool knows(int a, int b);

class Solution {
public:
    /**
     * @param n a party with n people
     * @return the celebrity's label or -1
     */
    int findCelebrity(int n) {
        // Write your code here
        int i = 0; 
        for(int j = 1; j < n; j++){
            i = knows(j, i) ? i : j; 
        }
        for(int j = 0; j < n; j++){
            if(i == j){
                continue; 
            }
            if(knows(i, j) || !knows(j, i)){
               return -1; 
            }
        }
        return i; 
    }
};

Comments

Popular posts from this blog

1427. Split Array into Fibonacci Sequence

Amazon OA 763. Partition Labels

05/25 周一