敢教日月换新天。为有牺牲多壮志,

[Swift]LeetCode277. 寻找名人 $ Find the Celebrity

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10685785.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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 - 1people 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.


 如果你在一个有N个人的聚会上(从0到N-1),找到你的名人,其中可能有一个名人。名人的定义是所有其他人都认识他/她,但他/她不认识他们中的任何一个。

 现在你想知道名人是谁,或者确认没有名人。你唯一可以做的就是问这样的问题:“你好,A。你认识B吗?”为了得到A是否知道B的信息,你需要通过尽可能少的提问(在渐近意义上)来找出名人(或者验证没有名人)。 

您将得到一个helper函数bool knowns(a,b),该函数告诉您a是否知道b。实现一个函数int findcelebrity(n),您的函数应该最小化要知道的调用数。

注:如果他/她在聚会上,就只有一个名人。如果派对上有名人,请退回名人的标签。如果没有名人,返回-1。


Solution:

复制代码
 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 }
复制代码

 

posted @   为敢技术  阅读(267)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示
哥伦布
09:09发布
哥伦布
09:09发布
3°
多云
东南风
3级
空气质量
相对湿度
47%
今天
中雨
3°/15°
周三
中雨
3°/13°
周四
小雪
-1°/6°