Find the Celebrity

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Find the Celebrity相关的知识,希望对你有一定的参考价值。

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

1. Use the condition : he/she knows no one. So you can get candidate by filtering out whether a candidate knows somebody.

2. Use the condition : all others know him/her. So check whether one of others does not know him/her, or he/she knows somebody.

以上是关于Find the Celebrity的主要内容,如果未能解决你的问题,请参考以下文章

Find the Celebrity

Find the Celebrity

277. Find the Celebrity

277. Find the Celebrity

277. Find the Celebrity

277. Find the Celebrity