-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path277.find-the-celebrity.js
63 lines (57 loc) · 1.21 KB
/
277.find-the-celebrity.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* @lc app=leetcode id=277 lang=javascript
*
* [277] Find the Celebrity
*/
/**
* Definition for knows()
*
* @param {integer} person a
* @param {integer} person b
* @return {boolean} whether a knows b
* knows = function(a, b) {
* ...
* };
*/
/**
* @param {function} knows()
* @return {function}
*/
/*
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.
*/
function knowOther(person, total, knows) {
for (let i = 0; i < total; i++) {
if (person != i && knows(person, i)) {
return true;
}
}
return false;
}
function allOthersKnowHim(person, total, knows) {
for (let i = 0; i < total; i++) {
if (person != i && !knows(i, person)) {
return false;
}
}
return true;
}
var solution = function(knows) {
/**
* @param {integer} n Total people
* @return {integer} The celebrity
*/
/*
I thinks knows implementation utilize
grapth first from n
*/
return function(n) {
// for each person, check whether he knows any other&& other know him
for (let i = 0; i < n; i++) {
if (!knowOther(i, n, knows) && allOthersKnowHim(i, n, knows)) {
return i;
}
}
return -1;
};
};