★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-ycxgzxyh-ky.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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.git
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).github
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
.函數
若是你在一個有N我的的聚會上(從0到N-1),找到你的名人,其中可能有一個名人。名人的定義是全部其餘人都認識他/她,但他/她不認識他們中的任何一個。spa
如今你想知道名人是誰,或者確認沒有名人。你惟一能夠作的就是問這樣的問題:「你好,A。你認識B嗎?」爲了獲得A是否知道B的信息,你須要經過儘量少的提問(在漸近意義上)來找出名人(或者驗證沒有名人)。 code
您將獲得一個helper函數bool knowns(a,b),該函數告訴您a是否知道b。實現一個函數int findcelebrity(n),您的函數應該最小化要知道的調用數。orm
注:若是他/她在聚會上,就只有一個名人。若是派對上有名人,請退回名人的標籤。若是沒有名人,返回-1。htm
Solution:blog
1 class Solution { 2 func findCelebrity(_ n:Int) -> Int { 3 var res:Int = 0 4 for i in 0..<n 5 { 6 if knows(res, i) 7 { 8 res = i 9 } 10 } 11 for i in 0..<n 12 { 13 if res != i && (knows(res, i) || !knows(i, res)) 14 { 15 return -1 16 } 17 } 18 return res 19 } 20 }