Saturday, August 24, 2019

Leetcode 277: Find the Celebrity

https://leetcode.com › problems › find-the-celebrity


Notes:

One way to think about this question is that: for each pair of (i, j), once we find i know j, or j doesn't know i, then i is not a celebrity. Otherwise, if i doesn't know j, but j knows i. Then j is not celebrity neither. See the code below:

  1. bool knows(int a, int b);
  2. class Solution {
  3. public:
  4.     int findCelebrity(int n) {
  5.         vector<bool> candidate(n, true);//memorize the results
  6.         for (int i = 0; i < n; ++i) {
  7.             for (int j = 0; j < n; ++j) {//compare i with all the rest
  8.                 if (candidate[i] && i != j) {
  9.                     if (knows(i, j) || !knows(j, i)) {
  10.                         candidate[i] = false;
  11.                         break;
  12.                     } else {
  13.                         candidate[j] = false;
  14.                     }
  15.                 }
  16.             }
  17.             if (candidate[i]) return i;
  18.         }
  19.         return -1;
  20.     }
  21. };

No comments:

Post a Comment