原题链接在这里:https://leetcode.com/problems/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
.
题解:
先找一个candidate. 若是celebrity 认识 i, 说明i 有可能是celebrity. 就更新i为candidate.
找到这个candidate 后 再扫一遍来判定这是不是一个合格的candidate, 若是出现candidate认识i 或者 i不认识candidate的情况, 说明这不是一个合格的candidate.
Time Complexity: O(n). Space: O(1).
AC 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 if(n <= 1){ 7 return -1; 8 } 9 int celebrity = 0; 10 //找一个candidate 11 for(int i = 0; i<n; i++){ 12 if(knows(celebrity, i)){ 13 celebrity = i; 14 } 15 } 16 for(int i = 0; i<n; i++){ 17 //若是出现candidate认识i 或者 i不认识candidate的情况, 说明这不是一个合格的candidate 18 if(i != celebrity && (knows(celebrity, i) || !knows(i, celebrity))){ 19 return -1; 20 } 21 } 22 return celebrity; 23 } 24 }