[LeetCode] 277. Find the Celebrity

linspiration發表於2019-01-19

Problem

Suppose you are at a party with n people (labeled from 0 to n – 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n – 1 people know him/her but he/she does not know any of them.

Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: “Hi, A. Do you know B?” to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).

You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows.

Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity`s label if there is a celebrity in the party. If there is no celebrity, return -1.

Solution

Three cases:

  1. Everyone knows someone else, return -1;
  2. No one knows each other, return -1;
  3. One doesn`t know anyone, every one else knows someone but not necessarily him, return -1;
  4. Everyone knows him but he also knows someone, return -1;
  5. Everyone knows him and he doesn`t know anyone, return suspect.
public class Solution extends Relation {
    public int findCelebrity(int n) {
        int suspect = 0;
        for (int i = 1; i < n; i++) {
            //suspect shouldn`t know anyone, if he knows i, set i as new suspect
            if (knows(suspect, i)) suspect = i; 
        }
        for (int i = 0; i < n; i++) {
            //new suspect has been good so far, but double check
            if (i != suspect && (knows(suspect, i) || !knows(i, suspect))) return -1; 
        }
        return suspect;
    }
}

two for-loops with HashMap

if it removes the requirement that celebrity shouldn`t know anyone else, can do this:

public class Solution extends Relation {
    public int findCelebrity(int n) {
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < n-1; i++) {
            for (int j = i+1; j < n; j++) {
                if (knows(i, j)) {
                    map.put(j, map.getOrDefault(j, 0)+1);
                }
                if (knows(j, i)) {
                    map.put(i, map.getOrDefault(i, 0)+1);
                }
                if (map.containsKey(i) && map.get(i) == n-1) res.add(i);
                if (map.containsKey(j) && map.get(j) == n-1) res.add(j);
            }
        }
        if (res.size() == 0 || res.size() > 1) return -1;
        return res.get(0);
    }
}

相關文章