Skip to content

Commit 85b8d7c

Browse files
committed
add two pointers solution for find the celebrity
1 parent 336c349 commit 85b8d7c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/main/java/joshua/leetcode/array/FindCelebrity.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package joshua.leetcode.array;
22

3+
import joshua.leetcode.solutiontag.TwoPointers;
4+
35
import java.util.LinkedList;
46
import java.util.List;
57

@@ -93,4 +95,27 @@ public int findCelebrity(int n) {
9395
return celebrity;
9496
}
9597
}
98+
99+
@TwoPointers
100+
public abstract static class Solution2 extends FindCelebrity {
101+
102+
103+
@Override
104+
public int findCelebrity(int n) {
105+
int l = 0;
106+
int r = n -1;
107+
while ( l < r) {
108+
if (knows(l, r)) ++l;
109+
else r--;
110+
}
111+
for (int i = 0; i < n; i ++) {
112+
if (i != l) {
113+
if (knows(i, l) || !knows(l, i)) return -1;
114+
}
115+
}
116+
return l;
117+
}
118+
119+
120+
}
96121
}

0 commit comments

Comments
 (0)