Problem:

Analysis:
method1:
first of all, we can use the array with 2 dimensions to check each pair, which time complexity will be O(n^2)
method2:
- the first pass for all the people, find the celebrity candidate who doesn’t know anyone.
- if (knows(A, B)):
* A is not Celebrity; - else:
* B is not Celebrity }
- the second pass, to make sure that the candidate is indeed the celebrity, or return -1;
/**
*
* @author shaohua
*boolean knows(A, B)
*
* 1. find the celebrity candidate who doesn't know the person behind him
* 2. make sure candidate is celebrity
*
*/
public class Solution1 {
public int findCelebrity(int n) {
int candidate = 0;
for (int i=1; i<n; i++) {
if (knows(candidate, i)) {
candidate = i;
}
}
for(int i=0; i<n; i++) {
if (candidate == i) {
continue;
}
if (knows(candidate,i) || !knows(i,candidate)) {
return -1;
}
}
return candidate;
}
}
本文探讨了在一组人中快速识别出唯一名人的算法。首先通过一次遍历找到可能的名人候选,再进行二次验证确认其是否为真正的名人,整体时间复杂度为O(n)。文章详细解释了算法原理及其实现过程。
579

被折叠的 条评论
为什么被折叠?



