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.
原文:http://www.cnblogs.com/shuashuashua/p/5634688.html