-
Notifications
You must be signed in to change notification settings - Fork 110
/
277-find-the-celebrity.cpp
57 lines (53 loc) · 1.42 KB
/
277-find-the-celebrity.cpp
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
// Time: O(N), Space: O(1)
// Forward declaration of the knows API.
bool knows(int a, int b);
class Solution {
public:
int findCelebrity(int n) {
int candidate = 0;
for (int i = 1; i < n; i++) {
if (knows(candidate, i)) {
candidate = i;
}
}
for (int i = 0; i < n; i++) {
if (i == candidate) continue;
if (!knows(i, candidate) || knows(candidate, i)) {
return -1;
}
}
return candidate;
}
};
// Time: O(N^2), Space: O(N)
// Forward declaration of the knows API.
bool knows(int a, int b);
class Solution {
public:
struct Degrees {
int in;
int out;
Degrees(int i, int o): in(i), out(o) {}
};
int findCelebrity(int n) {
vector<Degrees> degrees(n, Degrees(0, 0));
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (knows(i, j)) {
degrees[i].out++;
degrees[j].in++;
}
if (knows(j, i)) {
degrees[j].out++;
degrees[i].in++;
}
}
}
for (int i = 0; i < n; i++) {
if (degrees[i].in == n - 1 && degrees[i].out == 0) {
return i;
}
}
return -1;
}
};