【Leetcode刷题】277. Find the Celebrity 搜寻名人
Link: leetcode277
(English version, 中文站需会员)
问题描述
相关Topics: Array, 贪心算法
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 about 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.
假设你和n个人(从0到n-1进行标注)在一个聚会上,这个聚会里可能存在一个名人。名人的定义是,其余n-1个人都认识他,但是他不认识任何人。
你希望找到谁是名人,或者证明这里不存在名人。你只能通过问问题的方式来得到信息,比如询问 “A,你认识B吗?” 来得到关于A是否认识B的信息,你要尽可能少的询问问题来找到正确答案。
给定一个bool的函数 knows(a, b) 来告诉你A是否认识B,实现int的函数findCelebrity(n),返回名人的标签(至多只有一个名人存在),如果没有名人的话,返回-1。
例子1
输入: graph = [[1,1,0],[0,1,0],[1,1,1]]
输出: 1
解释: 一共有三个人,0号和2号都认识1号,但是1号不认识他们,所以1号是名人,返回1。
例子2