KK's blog

每天积累多一些

0%

LeetCode 277 Find the Celebrity

LeetCode



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 the celebrity, but the celebrity 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 ask questions like: “Hi, A. Do you know B?” to get information about 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) that tells you whether A knows B. Implement a function int findCelebrity(n). There will be exactly one celebrity if they are at the party.

Return the celebrity’s label if there is a celebrity at the party. If there is no celebrity, return -1.

Example 1:



Input: graph = [[1,1,0],[0,1,0],[1,1,1]]
Output: 1
Explanation: There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody.


Example 2:



Input: graph = [[1,0,1],[1,1,0],[0,1,1]]
Output: -1
Explanation: There is no celebrity.


Constraints:

n == graph.length n == graph[i].length
2 <= n <= 100 graph[i][j] is 0 or 1.
graph[i][i] == 1

Follow up: If the maximum number of allowed calls to the API knows is `3
n`, could you find a solution without exceeding the maximum number of calls?

题目大意:

通过调用a是否认识b函数,找出名人。名人是除自己的所有人都认识他,他不认识其他所有人

解题思路:

类似于LeetCode 169 Majority Element,用水王法

解题步骤:

  1. 找出可能名人,通过查看是否i后面的每一个人都认识i,若不是将candidate换成当前下标
  2. 按定义验证第一步的结果是否名人,两步验证

注意事项:

  1. 按照定义,若i不认识candiate才换candidate,用not。因为edge case是没有边或者图存在循环
  2. 验证时候,第二步验证candidate若认识任意人就不是名人,排除candidate认识自己。题目条件candidate认识自己。

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def findCelebrity(self, n: int) -> int:
# find potential candidate
candidate = 0
for i in range(1, n):
if not knows(i, candidate):
candidate = i
# validate
for i in range(n):
if not knows(i, candidate):
return -1
for i in range(n):
if candidate != i and knows(candidate, i):
return -1
return candidate

算法分析:

时间复杂度为O(n),空间复杂度O(1)

Free mock interview