*Find the Celebrity
2016-01-02 07:33
288 查看
Suppose you are at a party with
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
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
reference: https://leetcode.com/discuss/56413/java-solution-two-pass
npeople (labeled from
0to
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.
class Solution extends Relation { public int findCelebrity(int n) { int candidate = 0; for(int i = 1; i < n; i++){ if(knows(candidate, i)&&!knows(i,candidate)) candidate = i; } for(int i = 0; i < n; i++){ if(i != candidate) { if(knows(candidate, i) || !knows(i, candidate)) return -1; } } return candidate; } }
reference: https://leetcode.com/discuss/56413/java-solution-two-pass
相关文章推荐
- 预处理...
- typedef的使用...typedef int (*Func)(int,int); Func func = sum;
- Leetcode: Maximum Product of Word Lengths
- juqery中checkbox的click事件
- *Paint House
- 极客DIY:使用Arduino制作一块开源手表
- ios学习顺序表
- 二.OC基础--1,对象的存储细节,2,#pragma mark指令,3,函数和对象方法的区别,4,对象和方法之间的关系 ,5.课堂习题
- 一.OC基础之:1,OC语言的前世今生 ,2,OC语言入门,3,OC语言与C的差异,4,面向对象,5,类和对象的抽象关系,6,类的代码创建,7,类的成员组成及访问
- 1.import和include区别 2.NSLog 和printf区别 3.创建对象做的事情 4. 类和对象方法比较 5 匿名对象优缺点 6. 封装 7.作用域范围 8.id和instancetype 9.自定义构造方法规范 10.nil和Nil及NULL、NSNull区别
- C语言-1.static 和 extern使用,2.文件,3.数据块读写
- C语言-1.结构体,2.枚举,3.typedef,4.预处理指令的概念,5.条件编译
- 字符串输出输入函数,const修饰符,内存分区,动态内存管理,指针和函数,结构体
- c语言和oc对比
- Leetcode: Shortest Distance from All Buildings
- DELPHI编写服务程序总结
- 12306出现了这么多年为何还是如此渣
- 指针和数组的面试题
- [ES6] Function Params
- 小娜名言:有问题尽管问我i