Question
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.
Solution
先對N個人作編號,從1到N。先從編號1的人開始,問他認不認識編號2的人。
情況有兩種:
- 編號1認識編號2:那麼編號1一定不是名人,編號2有可能是名人。
- 編號1不認識編號2:編號2一定不是名人,因為名人要有N-1人認識他。
根據以上結果,可以得到結論:
- 編號1認識編號2:那麼編號1一定不是名人,編號2有可能是名人。
- 編號1不認識編號2:編號2一定不是名人,編號1有可能是名人。
每問一人就會淘汰掉一人,接著繼續問可能是名人的人選和下一個編號的關係,直到問完N個人就可以找出名人。時間複雜度是 O(N)。
1 | public int findCelebrity(int n) { |