Advertisement
1988coder

277. Find the Celebrity

Nov 28th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1. /* The knows API is defined in the parent class Relation.
  2.       boolean knows(int a, int b); */
  3.  
  4. /*
  5. 2 Pass Solution
  6. Time Complexity: O(n)
  7. Space Complexity: O(1)
  8. */
  9. public class Solution extends Relation {
  10.     public int findCelebrity(int n) {
  11.         if (n < 1) {
  12.             return -1;
  13.         }
  14.         if (n == 1) {
  15.             return 0;
  16.         }
  17.        
  18.         int celeb = 0;
  19.        
  20.         for (int i = 1; i < n; i++) {
  21.             if(knows(celeb, i)) {
  22.                 celeb = i;
  23.             }
  24.         }
  25.        
  26.         for (int i = 0; i < n; i++) {
  27.             if (i == celeb) {
  28.                 continue;
  29.             }
  30.             if (i < celeb && knows(celeb, i)) {
  31.                 return -1;
  32.             }
  33.             if (!knows(i ,celeb)) {
  34.                 return -1;
  35.             }
  36.         }
  37.        
  38.         return celeb;
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement