算法题:名人问题,给出最优解法
def findCelebrity(int n): celebrity = 0 for i in range(1, n): if knows(celebrity, i): celebrity = i for i in range(n): if (celebrity != i and knows(celebrity, i)): return -1 if (celebrity != i and !knows(i, celebrity)): return -1 return celebrity如果a认识b,则a不会是名人;如果a不认识b,则b不会是名人。因此每询问一次a是否认识b,都可以排除掉一个人,所以在O(n)时间内就可以排除掉n-1个人。 最后还要检查确认,是否其他人都认识这个人,以及这个人都不认识其他人。
int findCelebrity(int n) { if(n == 1) return 0; int cand = 0; //假设名人为0 for(int other = 1; other < n; ++other) { if(!know(other, cand) || know(cand, other)) //cand一定不是名人 cand = other; else continue; } for(int i = 0; i < n; ++i) { if(cand == i) continue; if(know(cand, i) || !know(i, cand)) return -1; } return cand; }