[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). 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.

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.

Note:

  1. The directed graph is represented as an adjacency matrix, which is an n x n matrix where a[i][j] = 1 means person i knows person j while a[i][j] = 0 means the contrary.
  2. Remember that you won't have direct access to the adjacency matrix.

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

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

时间O(n)

空间O(1)

Java实现

 1 /* The knows API is defined in the parent class Relation.
 2       boolean knows(int a, int b); */
 3 
 4 public class Solution extends Relation {
 5     public int findCelebrity(int n) {
 6         int candidate = 0;
 7         for (int i = 1; i < n; i++) {
 8             if (knows(candidate, i)) {
 9                 candidate = i;
10             }
11         }
12 
13         // double check
14         for (int i = 0; i < n; i++) {
15             if (i != candidate && (knows(candidate, i) || !knows(i, candidate))) {
16                 return -1;
17             }
18         }
19         return candidate;
20     }
21 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12867117.html