leetcode277- Find the Celebrity- medium
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
.
算法:关键是每问一次问题必定可以淘汰一个人。时间复杂度是O(n)。第一次遍历循环问一个问题,可以只剩下一个人。第二次遍历循环问两个问题,可以确定这个人是不是真金。
1.空间复杂度O(n):用Queue来存candidates,每次拉出来,重新推进去那个没被淘汰的。
2.空间复杂度O(1):用一个int变量来存往前走一路一直只剩下的唯一的那个candidate。
细节:final是java关键字,命名的时候不能用,可以用last替代。
1.空间复杂度O(n): queue
/* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ public class Solution extends Relation { public int findCelebrity(int n) { if (n <= 1) { return -1; } Queue<Integer> candidates = new LinkedList<>(); for (int i = 0; i < n; i++) { candidates.offer(i); } while (candidates.size() > 1) { int a = candidates.poll(); int b = candidates.poll(); if (knows(a, b)) { candidates.offer(b); } else { candidates.offer(a); } } int last = candidates.poll(); for (int i = 0; i < n; i++) { if (i == last) { continue; } if (knows(last, i) || !knows(i, last)) { return -1; } } return last; } }
2.空间复杂度O(1)
/** * 本参考程序来自九章算法,由 @九章算法 提供。版权所有,转发请注明出处。 * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。 * - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班, * - Big Data 项目实战班,算法面试高频题班, 动态规划专题班 * - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code */ // version: 高频题班 public class Solution extends Relation { /** * @param n a party with n people * @return the celebrity's label or -1 */ public int findCelebrity(int n) { // Write your code here int ans = 0; for (int i = 1; i < n; i++) { if (knows(ans, i)) { ans = i; } } for (int i = 0; i < n; i++) { if (ans != i && knows(ans, i)) { return -1; } if (ans != i && !knows(i, ans)) { return -1; } } return ans; } }