congr / world

2 stars 1 forks source link

LeetCode : 277. Find the Celebrity #483

Closed congr closed 5 years ago

congr commented 5 years ago

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

image

congr commented 5 years ago

very tricky, O(N)

/* The knows API is defined in the parent class Relation.
      boolean knows(int a, int b); */

public class Solution extends Relation {
    public int findCelebrity(int n) {
        int candi = 0;
        for (int i = 1; i < n; i++) {
            if (knows(candi, i)) candi = i; // candi switch
        }

        for (int i = 0; i < n; i++) {
            if (candi == i) continue;

            if (knows(candi, i) || !knows(i, candi)) return -1;
        }

        return candi;
    }
}