4th__277. Find the Celebrity__【400_LeetCode之路】

方法一:双层循环;否命题判定candidate[i]  相反命题判定candidate[j]

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


//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.
//看起来像是暴力破解法
class Solution {
public:
	int findCelebrity(int n) {
		vector<bool> candidate(n, true);		//对 candidate 标记成 true 或 false
		for (int i = 0; i < n; ++i) {
			for (int j = 0; j < n; ++j) {
				if (candidate[i] && i != j) {
					if (knows(i, j) || !knows(j, i)) {		//如果i认识j,或者j不认识i,说明i不可能是名人,那么我们标记其为false
						candidate[i] = false;
						break;
					}
					else {		//反之如果i不认识j,或者j认识i,说明j不可能是名人
						candidate[j] = false;
					}
				}
			}
			if (candidate[i]) return i;		//限定了只有1个或0个名人。对于每个候选者i,如果遍历了一圈而其候选者状态仍为true,说明i就是名人
		}
		return -1;		//如果遍历完所有人没有找到名人,返回-1
	}
};

方法二:如果j一直循环到结尾了,并没有break for循环,说明i是候选人,如果中途break了for循环, j==n不会成立。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


//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.


class Solution {
public:
	int findCelebrity(int n) {
		for (int i = 0, j = 0; i < n; ++i) {
			for (j = 0; j < n; ++j) {
				if (i != j && (knows(i, j) || !knows(j, i))) break;		//我们对于不是名人的i,直接break,继续检查下一个,但是由于我们没有标记后面的候选人的状态 candidate,所以有可能会重复调用一些knows函数
			}
			if (j == n) return i;		//如果j一直循环到结尾了,并没有break for循环,说明i是候选人,如果中途break了for循环, j==n不会成立。
		}
		return -1;
	}



private:
	bool knows(int a_input, int b_input){
		//空着,是题目中包含的

	}
};

方法三:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


//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.


class Solution {
public:
	int findCelebrity(int n) {
		int res = 0;
		for (int i = 0; i < n; ++i) {		//有没有可能res认识两个人呢?不可能,res只认识一个人  或者一个都不认识
			if (knows(res, i)) res = i;
		}
		for (int i = 0; i < n; ++i) {
			if (res != i && (knows(res, i) || !knows(i, res))) return -1;		//我们来检测候选人res是否真正是名人,我们如果判断不是名人,则返回-1
		}
		return res;
	}




private:
	//其中应该包含 自己和自己 相认 是false 的选项
	bool knows(int a_input, int b_input) {
		//空着,是题目中包含的

	}
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值