MS 645. Find the Celebrity
// 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
Post a Comment