博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-Find the Celebrity
阅读量:4611 次
发布时间:2019-06-09

本文共 1209 字,大约阅读时间需要 4 分钟。

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.

Solution:

/* 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;        for (int i=1;i

 

转载于:https://www.cnblogs.com/lishiblog/p/5838920.html

你可能感兴趣的文章
【openlayers】CSS3样式的Popups
查看>>
常用表单及控件测试用例检查点总结
查看>>
UVA5874 Social Holidaying 二分匹配
查看>>
网络流24题 餐巾计划(费用流)
查看>>
Codeforces Round #478 (Div. 2) D Ghosts 会超时的判断两个之间关系,可以用map
查看>>
Redis之Hash
查看>>
mysql 相關
查看>>
支持新版chrome,用webstorm编译形成css和sourcemap,调试sass和less源文件
查看>>
Climbing Stairs
查看>>
用来武装Firebug的十四款Firefox插件
查看>>
几种常用排序算法代码实现和基本优化(持续更新ing..)
查看>>
css样式之超出隐藏
查看>>
python-scrapy框架
查看>>
java.lang.OutOfMemoryError: bitmap size exceeds VM budget
查看>>
Java解惑精炼版(一)
查看>>
无法获得锁 /var/lib/dpkg/lock - open
查看>>
自己写数据库访问ORM
查看>>
多项式填坑。。?
查看>>
webapi同一个Controller多个函数
查看>>
ASP.NET Web API身份验证和授权
查看>>