1. 程式人生 > >名人問題 算法 時間復雜度

名人問題 算法 時間復雜度

tco form possible rom which 一道 number 個人 get

這是一道leetcode上面的題目,同時也是Anany的算法書的一道課後題

題目貼在這裏

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.

中文簡單翻譯

如果一個人A是名人,那麽其他的n-1個人都認識A,而且A不認識其他的n-1個人。這題的目標是要從n個人中找出其中的名人,如果沒有,則告知其中沒有名人。你只能通過詢問他人“你認識他(她)嗎?”來找出名人

如果我們不用什麽優解,直接暴力呢

問一個人是否認識剩下的所有人,O(n-1),然後剩下的也挨個問
O(n(n?1)/2),時間復雜度是n方

采用高效一點的算法呢

從n個人中任意挑兩個人a,b出來,詢問a是否認識b

1.a認識b,a不是名人,排除a

2.a不認識b,b不是名人,排除b

通過這樣的詢問,每次詢問以後只能排除一個人。如果我們不斷地重復的這個過程,直到只剩下一個人,那麽我們會做n-1次對比。而剩下這個人是唯一可能成為名人的人,那麽我們需要詢問剩下的n-1個人是否認識他,也需要詢問他是否認識剩下的n-1個人。

那麽就是2(n-1)+n-1=3(n-1) 最多問3n-3個問題

時間復雜度是O(n)的

名人問題 算法 時間復雜度