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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,157評論 0 23
  • 一 船成了擺設(shè) 漁鷹和鴨子一起圈養(yǎng) 父親把爐火燒得旺旺地 在爐子旁邊烤旱煙 滿屋子干燥煙草味 嗆得蹲在地上織席的母...
    碧荷聽雨閱讀 624評論 0 0
  • 01 今天的主題來自一位女生的提問。來自一位女生。 話說她的話題好沉重的,在這樣的話題下,我很難過,更是不安與無力...
    我就是貓姐閱讀 633評論 1 4
  • 申辰林/文 01 好友在淘寶上買了五六件衣服,收到快遞時迫不及待的撕開包裝,像表演服裝秀似的一件件試穿給我看,給我...
    申辰林閱讀 605評論 7 7
  • 處于水深火熱中的暑假,在一個山清水秀的絕佳旅行地點(diǎn)旅游何嘗不是一件快活之事,但我對這個地方的回憶不僅僅是景了,還明...
    GJRRRRR閱讀 306評論 0 0

友情鏈接更多精彩內(nèi)容