本题不算难,但是其实并不好想到277. Find the Celebrity - 图1的算法

    celebriy:

    • 所有人都知道他
    • 他不知道任何人

    最核心的代码是First Pass:

    1. for (int i = 1; i < n; ++i) {
    2. if (knows(candidate, i)) {
    3. // update candidate
    4. candidate = i;
    5. }
    6. }
    • 如果Candidate不知道别人:
      • 如果candidate是celebrity,那那个别人一定不是celebrity
      • 如果candidate不是celebrity,那那个别人也一定不是celebrity,否则会被认出
    • 一旦candidate知道了别人,立刻把潜在的candidate换成这个人,因为原来的candidate已经不符合题意了

    只要有celebrity的存在,则他一定就是就是candidate,但是celebrity也可能不存在,所以我们要做二次验证。

    • 时间复杂度:277. Find the Celebrity - 图2
    • 空间复杂度: 277. Find the Celebrity - 图3

    最终代码如下:

    1. /* The knows API is defined in the parent class Relation.
    2. boolean knows(int a, int b); */
    3. public class Solution extends Relation {
    4. public int findCelebrity(int n) {
    5. int candidate = 0;
    6. for (int i = 1; i < n; ++i) {
    7. if (knows(candidate, i)) {
    8. // update candidate
    9. candidate = i;
    10. }
    11. }
    12. for (int i = 0; i < n; ++i) {
    13. if (candidate == i) {
    14. continue;
    15. }
    16. if (knows(candidate, i) || !knows(i, candidate)) {
    17. return -1;
    18. }
    19. }
    20. return candidate;
    21. }
    22. }