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.

一刷
2 pass

/* 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;
        //celebrity don't know others
        for(int i=1; i<n; i++){
            if(knows(candidate, i)) candidate = i;
        }
        
        //all is know celebrity
        for(int i=0; i<n; i++){
            if(i == candidate) continue;
            if(!knows(i, candidate) || knows(candidate, i)) return -1;
        }
        return candidate;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,472评论 0 23
  • 一 船成了摆设 渔鹰和鸭子一起圈养 父亲把炉火烧得旺旺地 在炉子旁边烤旱烟 满屋子干燥烟草味 呛得蹲在地上织席的母...
    碧荷听雨阅读 3,599评论 0 0
  • 01 今天的主题来自一位女生的提问。来自一位女生。 话说她的话题好沉重的,在这样的话题下,我很难过,更是不安与无力...
    我就是猫姐阅读 3,682评论 1 4
  • 申辰林/文 01 好友在淘宝上买了五六件衣服,收到快递时迫不及待的撕开包装,像表演服装秀似的一件件试穿给我看,给我...
    申辰林阅读 3,547评论 7 8
  • 处于水深火热中的暑假,在一个山清水秀的绝佳旅行地点旅游何尝不是一件快活之事,但我对这个地方的回忆不仅仅是景了,还明...
    GJRRRRR阅读 1,716评论 0 0