Skip to content

Commit d772b0e

Browse files
add a solution for 142
1 parent 1bfd15f commit d772b0e

File tree

1 file changed

+26
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+26
-0
lines changed

src/main/java/com/fishercoder/solutions/_142.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,35 @@
22

33
import com.fishercoder.common.classes.ListNode;
44

5+
import java.util.HashSet;
6+
import java.util.Set;
7+
58
public class _142 {
69

710
public static class Solution1 {
11+
public ListNode detectCycle(ListNode head) {
12+
Set<ListNode> seen = new HashSet<>();
13+
while (head != null) {
14+
if (!seen.add(head)) {
15+
return head;
16+
}
17+
head = head.next;
18+
}
19+
return null;
20+
}
21+
}
22+
23+
public static class Solution2 {
24+
/**
25+
* This comment explains it really well for this solution:
26+
* https://leetcode.com/problems/linked-list-cycle-ii/discuss/44774/Java-O(1)-space-solution-with-detailed-explanation./44281
27+
*
28+
* When fast and slow meet for the first time at point P, fast travelled (a + b + c + b)
29+
* and slow travelled (a + b), and we know fast travels twice fast as slow, so we have:
30+
* a + b + c + b = 2*(a + b), this gives us a == c;
31+
* so at point P, we start a new slow2 pointer from the head, when both slow and slow2 travelled distance a, they must meet
32+
* at cycle entrance point Q.
33+
*/
834
public ListNode detectCycle(ListNode head) {
935
ListNode slow = head;
1036
ListNode fast = head;

0 commit comments

Comments
 (0)