Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd772b0e

Browse files
add a solution for 142
1 parent1bfd15f commitd772b0e

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
importcom.fishercoder.common.classes.ListNode;
44

5+
importjava.util.HashSet;
6+
importjava.util.Set;
7+
58
publicclass_142 {
69

710
publicstaticclassSolution1 {
11+
publicListNodedetectCycle(ListNodehead) {
12+
Set<ListNode>seen =newHashSet<>();
13+
while (head !=null) {
14+
if (!seen.add(head)) {
15+
returnhead;
16+
}
17+
head =head.next;
18+
}
19+
returnnull;
20+
}
21+
}
22+
23+
publicstaticclassSolution2 {
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
publicListNodedetectCycle(ListNodehead) {
935
ListNodeslow =head;
1036
ListNodefast =head;

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp