[LeetCode] 277. Find the Celebrity 寻找名人
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个人,其中有一位名人。名人的定义是其他n-1个人都认识他,但他不认识任何一个人。要找出这位名人,只允许问A是否认识B。实施一个函数,找出名人,如果有返回他的label,如果没有返回-1。
解法1: Brute force, 用一维数组标记候选人状态,初始化为true,然后验证每一个人是否为名人。对于候选者i,遍历所有其他人j,如果i认识j,或者j不认识i,说明i不可能是名人,标记其为false。T: O(n^2), S: O(n)
解法2: 先设定候选人res为0,从1开始遍历数组,对于遍历到的人i,若候选人res认识i,则将候选人res设为i。第一次遍历完毕以后,再开始第二次遍历,来判断res是否确实为解。T: O(n), S: O(1)
Java:
public class Solution extends Relation { public int findCelebrity(int n) { if (n <= 1) return -1; int candidate = 0; for (int i = 1; i < n; i++) { if (knows(candidate, i)) candidate = i; } for (int i = 0; i < n; i++) { if (i != candidate && (knows(candidate, i) || !knows(i, candidate))) return -1; } return candidate; } }
Python:
class Solution(object): def findCelebrity(self, n): """ :type n: int :rtype: int """ candidate = 0 # Find the candidate. for i in xrange(1, n): if knows(candidate, i): # All candidates < i are not celebrity candidates. candidate = i # Verify the candidate. for i in xrange(n): if i != candidate and (knows(candidate, i) \ or not knows(i, candidate)): return -1 return candidate
C++: Solution 1
class Solution { public: int findCelebrity(int n) { vector<bool> candidate(n, true); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (candidate[i] && i != j) { if (knows(i, j) || !knows(j, i)) { candidate[i] = false; break; } else { candidate[j] = false; } } } if (candidate[i]) return i; } return -1; } };
C++: Solution 2
class Solution { public: int findCelebrity(int n) { int res = 0; for (int i = 0; i < n; ++i) { if (knows(res, i)) res = i; } for (int i = 0; i < n; ++i) { if (res != i && (knows(res, i) || !knows(i, res))) return -1; } return res; } };
All LeetCode Questions List 题目汇总