[LC] 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)
. 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
.
/* 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 res = 0; // find the celebrity for (int i = 0; i < n; i++) { if (knows(res, i)) { res = i; } } // return -1 if res is not celebrity for (int i = 0; i < n; i++) { if (i != res && (knows(res, i) || !knows(i, res))) { return -1; } } return res; } }
原文地址:https://www.cnblogs.com/xuanlu/p/11896128.html
- Go语言实践:从新手入门到上线真实的小型服务所遇到的那些坑
- 4个简单的数据管理技巧
- MongoDB的设计模式策略
- 如何用容器实现生产级Redis sharding集群一键交付
- Hadoop旧mapreduce的map任务切分原理
- 解读Neo4j全新的Python驱动程序
- MySQL 5.7 X Plugin:流水线技术vs.并行查询技术
- 在下函数式编程,有何贵干?
- 基于Keras/Python的深度学习模型Dropout正则项
- 揭秘深度强化学习
- Swoole-2.0.1-Alpha 已发布,提供PHP原生协程支持
- Google核心技术之——PageRank算法scala实现
- 代码审查拯救世界?
- Kafka实战:从RDBMS到Hadoop,七步实现实时传输
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- PHP入门之数组
- PHP基础之排序
- 关于mysql limit offset的一点优化
- PHP基础之查找
- PHP木马免杀的一些总结
- PHP基础之面向对象篇
- PHP变量覆盖漏洞小结
- 算法复习 : 插入排序原理,记忆,时间复杂度 (7行java实现)
- PHP代码审计01之in_array()函数缺陷
- 分治思想 : 并归排序与其时间复杂度
- java Spring系列之 配置文件的操作 +Bean的生命周期+不同数据类型的注入简析+注入的原理详解+配置文件中不同标签体的使用方式
- 算法系列1 初识算法 算法复杂性模型 算法复杂度的计算
- 树莓派基础实验32:DS1302实时时钟模块实验
- Failed to parse date ["1534467411000"]:Invalid time zone indicator '0'
- 快速排序 : 调优:3亿数据40秒,2亿数据30秒,1亿数据15秒