LeetCode 277. Find the Celebrity

来源:互联网 发布:淘宝加盟的骗局揭秘 编辑:程序博客网 时间:2024/04/30 21:48
#include <vector>#include <iostream>using namespace std;/*  Suppose you are at the party with N people 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 she doesn't  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 by asking as few questions as possible.  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.*/// if A knows B, return true, otherwise, return false.// This is to use binary search.bool knows(int a, int b);int findCelebrity(int n) {  int i = 0;  int j = n; int celebrity = 0;  while(i < j) {    if(knows(i, j)) {celebrity = j; i++;} // if i knows j, i is absolutely not the celebrity.  }  for(int k = 0; k < n; ++k) { if(k == celebrity) continue;    if(knows(celebrity, k) || !knows(k, celebrity)) return -1;  // verify whether the celebrity really exists.  }  return celebrity;}

This question need a bit analysis. Suppose, we know [A][B]  == 1 stands for A knows B. To minimize the problem, we can suppose that the party has 5 people. A, B, C, D, E

we use a matrix to remember their relationship.

For example:

      A   B   C   D   E

A    1    1   0   1    1

B    0    1   0   0    0

C    1    1   1   0    0

D    1    1   1   1    1

E    1    1   1   0    1   

in this matrix, it is pretty clear that B is the celebrity. Everyone knows B, but B doesn't know everyone else. We can first suppose A is the pseudo-celebrity, in matrix[0][0], A knows A, A stays the pseudo-celebrity, A knows B in Matrix[0][1], B become the pseudo-celebrity. matrix[1][2] == 0, B stays the pseudo-celebrity, matrix[1][3] == 0, B stays the pseudo-celebrity, matrix[1][4] == 0, B stays  the pseudo-celebrity.

Now, we have check B against all the people in the party, B might be the celebrity. We, however, need to check B against all people in this party one by one.

Matrix[A][B] == 1 && matrix[B][A] == 0, Matrix[C][B] == 1 && Matrix[B][C] == 0, Matrix[D][B] == 1 && Matrix[B][D] == 0 && Matrix[E][B] == 1 && Matrix[B][E] == 0. According to the definition, we can get that the B is the real celebrity.

0 0
原创粉丝点击