forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-champion-ii.cpp
46 lines (44 loc) · 993 Bytes
/
find-champion-ii.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
// Time: O(n)
// Space: O(n)
// graph, hash table
class Solution {
public:
int findChampion(int n, vector<vector<int>>& edges) {
vector<int> lookup(n);
for (const auto& e : edges) {
lookup[e[1]] = true;
}
int result = -1;
for (int u = 0; u < n; ++u) {
if (lookup[u]) {
continue;
}
if (result != -1) {
return -1;
}
result = u;
}
return result;
}
};
// Time: O(n)
// Space: O(n)
// graph, hash table
class Solution2 {
public:
int findChampion(int n, vector<vector<int>>& edges) {
unordered_set<int> lookup;
for (const auto& e : edges) {
lookup.emplace(e[1]);
}
if (size(lookup) != n - 1) {
return -1;
}
for (int u = 0; u < n; ++u) {
if (!lookup.count(u)) {
return u;
}
}
return -1;
}
};