名人问题 算法解析与Python 实现 O(n) 复杂度 （以Leetcode 277. Find the Celebrity为例）

1. 题目描述 Problem Description

Leetcode 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), 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.

（1）n个人中最多可以有几个名人？

(2) 如果其他n-1个人都认识A，但是A认识了n-1个人中其中一个人，那么A还是名人吗？

(3) 如果A不认识其他的n-1个人，但是n-1个人中有人不认识A，那么A还是名人吗？

-

(1) 他是否认识剩下的n-1个人： 最坏的情况需要调用knows(a,b)函数n-1次

(2) 剩下的n-1个人是否认识他：最坏的情况需要调用knows(a,b)函数n-1次

-

（1）a认识b：那么a肯定不是名人。

（2）b认识a：那么b肯定不是名人。

3. Python 实现

 1 # The knows API is already defined for you.
2 # @param a, person a
3 # @param b, person b
4 # @return a boolean, whether a knows b
5 # def knows(a, b):
6
7 class Solution(object):
8     def findCelebrity(self, n):
9         """
10         :type n: int
11         :rtype: int
12         """
13         if n == 0:
14             return -1
15         curr_stay = 0
16         for i in range(1, n):
17             if knows(curr_stay, i):
18                 curr_stay = i
19         for i in range(0, n):
20             if i == curr_stay:
21                 continue
22             if knows(curr_stay, i):
23                 return -1
24             if not knows(i, curr_stay):
25                 return -1
26         return curr_stay
27             

posted @ 2018-12-14 03:24 rgvb178 阅读(...) 评论(...) 编辑 收藏