LeetCode 277. Find the Celebrity

本文介绍了一种通过最少询问次数来找出派对中名人的算法。利用二分查找的思想,首先确定潜在名人,再验证其是否符合定义。文章详细解释了实现思路与步骤。
#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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值