Celebrity problem:
You have a room with n people. A celebrity walks in. Everyone knows the celebrity, the celebrity knows no one. Non-celebrities may/may not know anyone in the room. Give an algorithm to find the celebrity. Discuss the complexity.
做法:
O(N)的时间复杂度,按如上描述,名人最多一个,因此对于a1,a2,...,aN,我们依次判断
如果a1认识a2,则a1不是名人,将a1从上述数组中删去,我们接着从a2开始判断重复上一过程
如果a1不认识a2,则a2不是名人,则将a2从上述数组中删去,我们继续判断a1和a3的关系
因此每一轮这样的操作都能够删去一个人,最终只需要O(N)的时间就能识别出名人了
代码如下(未经测试,有错请报告):
bool know(int i,int j);//提供的API用以知晓I和J之间的认识关系
class Solution {
private:
unordered_set<int> cele,nonCele;
void addCele(int i){
if(nonCele.count(i)==0){
cele.insert(i);
}
}
void addNonCele(int i){
cele.erase(i);