forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_277.java
70 lines (65 loc) · 2.4 KB
/
_277.java
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
64
65
66
67
68
69
70
package com.fishercoder.solutions;
public class _277 {
public static class Solution1 {
/**
* Credit: https://leetcode.com/problems/find-the-celebrity/solution/ approach 2
* 1. we narrow down the possible celebrity candidate to only one person
* 2. we check to make sure that every other person knows
* this candidate and this candidate doesn't know any one of them, otherwise return -1
*
* We can think of this is a directed graph problem, a total of n vertices, the one vertex that has zero outgoing edges
* and n - 1 incoming edges is the celebrity.
*/
public int findCelebrity(int n) {
int candidate = 0;
for (int i = 1; i < n; i++) {
if (knows(candidate, i)) {
//this rules out the possibility that candidiate is a celebrity since he/she knows i
//so we update candidate to be i, because at least i doesn't know anybody yet.
candidate = i;
}
}
for (int i = 0; i < n; i++) {
if (i != candidate && (knows(candidate, i) || !knows(i, candidate))) {
return -1;
}
}
return candidate;
}
//this is a mock-up method to make IDE happy.s
boolean knows(int i, int candidate) {
return false;
}
}
public static class Solution2 {
/**
* My completely original solution on 10/21/2021, which turns out to match https://leetcode.com/problems/find-the-celebrity/solution/ Solution 1.
* Time: O(n^2)
* Space: O(1)
*/
public int findCelebrity(int n) {
for (int i = 0; i < n; i++) {
//check if i is the celebrity
int j = 0;
for (; j < n; j++) {
if (i != j) {
if (knows(i, j)) {
break;
}
if (!knows(j, i)) {
break;
}
}
}
if (j == n) {
return i;
}
}
return -1;
}
//this is a mock-up method to make IDE happy.s
boolean knows(int i, int candidate) {
return false;
}
}
}