forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindTheCelebrity.java
More file actions
54 lines (43 loc) · 1.24 KB
/
FindTheCelebrity.java
File metadata and controls
54 lines (43 loc) · 1.24 KB
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
package graph;
import java.util.HashMap;
import java.util.Map;
/**
* Description: https://leetcode.com/problems/find-the-celebrity
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(1) or O(n) with cache
*/
public class FindTheCelebrity {
private final Map<Relation, Boolean> cache = new HashMap<>();
public int findCelebrity(int n) {
int candidate = 0;
for (int man = 1; man < n; man++) {
if (cachedKnows(candidate, man)) {
candidate = man;
}
}
if (isCelebrity(candidate, n)) {
return candidate;
}
return -1;
}
private boolean isCelebrity(int candidate, int n) {
for (int man = 0; man < n; man++) {
if (man == candidate) continue;
if (cachedKnows(candidate, man) || !cachedKnows(man, candidate)) {
return false;
}
}
return true;
}
// use if API calls are expensive
private boolean cachedKnows(int a, int b) {
return cache.computeIfAbsent(new Relation(a, b), __ -> knows(a, b));
}
private record Relation(int a, int b) {
}
// API call
private boolean knows(int a, int b) {
return true;
}
}