[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 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. You are only allowed to 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:
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:
Example 2
Input: graph = [[1,0,1],[1,1,0],[0,1,1]]
Output: -1
Explanation: There is no celebrity.

Constraints:
n == graph.length == 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?

搜寻名人。

给一个API函数bool knows(a, b),以用来判断a是否认识b,认识返回true,不认识返回false。请你尽可能少的调用这个函数。

思路

思路是首先假设第一个人是名人的候选人 candidate,然后往后扫描,看这个名人是否不认识后面所有的人,期间只要有一次函数返回 false 则说明 candidate 不是名人,因为有人认识他。接着设认识 candidate 的人为 candidate,一直扫描到最后。因为存在没有名人的可能性所以还要扫描第二次来判断第一次找到的 candidate 是否真的是名人,第二次扫描的时候只要 candidate 认识任何一个人,或者有任何一个人不认识 candidate,则返回 -1,否则返回 candidate。

复杂度

时间O(n)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* 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) {
int candidate = 0;
for (int i = 1; i < n; i++) {
if (knows(candidate, i)) {
candidate = i;
}
}

// double check
for (int i = 0; i < n; i++) {
if (i != candidate && (knows(candidate, i) || !knows(i, candidate))) {
return -1;
}
}
return candidate;
}
}

[LeetCode] 277. Find the Celebrity
https://shurui91.github.io/posts/1300749645.html
Author
Aaron Liu
Posted on
May 11, 2020
Licensed under