首页 > 其他 > 详细

Find the Celebrity

时间:2016-07-02 06:55:19      阅读:225      评论:0      收藏:0      [点我收藏+]
 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

原文:http://www.cnblogs.com/shuashuashua/p/5634688.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!