My code:
/* The knows API is defined in the parent class Relation.
boolean knows(int a, int b); */
public class Solution extends Relation {
public int findCelebrity(int n) {
if (n <= 0) {
return -1;
}
int candidate = 0;
for (int i = 1; i < n; i++) {
if (knows(candidate, i)) {
candidate = i;
}
}
for (int i = 0; i < n; i++) {
if (i == candidate) {
continue;
}
else if (!knows(i, candidate) || knows(candidate, i)) {
return -1;
}
}
return candidate;
}
}
邏輯題,interesting, 沒做出來。
reference:
https://discuss.leetcode.com/topic/23534/java-solution-two-pass
如果 a 不認(rèn)識(shí)任何人,不代表a是名人。
如果 a 不被任何人認(rèn)識(shí),不代表a是名人
只有當(dāng)a不認(rèn)識(shí)任何人,并且,a不被任何人認(rèn)識(shí),a才是名人
如果a 認(rèn)識(shí) b, a不可能是名人
如果a不認(rèn)識(shí)b,b不可能是名人
就是這幾個(gè)最重要的邏輯,搞清楚就行了。
Anyway, Good luck, Richardo! -- 09/04/2016