问题描述:
Suppose you are at a party with n
people (labeled from 0
to n - 1
) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1
people know him/her but he/she does not know any of them.
Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).
You are given a helper function bool knows(a, b)
which tells you whether A knows B. Implement a function int findCelebrity(n)
, your function should minimize the number of calls to knows
.
Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1
.
解题思路:
从n个人里面找名人,大家都认识名人,但是名人谁都不认识。
我没有特别好的方法然后就先写了暴力破解然后进行了剪枝。
看看这个人是不是谁都不认识,如果是的话,就跳出去,然后检查是不是大家都认识这个人。
但是我的运行效率并不算高。
且来看一下跑的最快的解法:
首先给candidate设定一个初始值为0
然后问ta认不认识相邻的人,如果ta认识,那么将candidate付给后面的人。
找到一个不认识ta后面所有的人的candidate
然后我们要检查所有的人是不是都认识ta,如果有认不认识,那说明没有。
接下来来检查ta是不是真的不认识所有人,后面的已经查过了,就看前面的了。
代码:
最快的解法:
// Forward declaration of the knows API.// Forward declaration bool knows(int a, int b); class Solution { public: int findCelebrity(int n) { int candidate = 0; for(int i = 0; i < n - 1; i++) { if(knows(candidate, i+1)) candidate = i+1; } for(int i = 0; i < n; i++) { if(i != candidate && !knows(i, candidate)) return -1; } for(int i = 0; i < candidate; i++) { if(knows(candidate, i)) return -1; } return candidate; } };
我的暴力破解:
// Forward declaration of the knows API. bool knows(int a, int b); class Solution { public: int findCelebrity(int n) { int celeb = -1; for(int i = 0; i < n; i++){ bool cel = true; for(int j = 0; j < n; j++){ if(i != j && knows(i,j)){ cel = false; break; } } if(cel){ celeb = i; break; } } if(celeb != -1){ for(int i = 0; i < n; i++){ if(i != celeb && !knows(i,celeb)){ return -1; } } } return celeb; } };