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

Commit6ecd814

Browse files
refactor 141
1 parent89d08ee commit6ecd814

File tree

1 file changed

+27
-53
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+27
-53
lines changed

‎src/main/java/com/fishercoder/solutions/_141.java

Lines changed: 27 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -5,59 +5,33 @@
55
importjava.util.HashSet;
66
importjava.util.Set;
77

8-
/**
9-
* 141. Linked List Cycle
10-
11-
Given a linked list, determine if it has a cycle in it.
12-
To represent a cycle in the given linked list, we use an integer
13-
pos which represents the position (0-indexed) in the linked list where tail connects to.
14-
If pos is -1, then there is no cycle in the linked list.
15-
16-
Example 1:
17-
Input: head = [3,2,0,-4], pos = 1
18-
Output: true
19-
Explanation: There is a cycle in the linked list, where tail connects to the second node.
20-
21-
Example 2:
22-
Input: head = [1,2], pos = 0
23-
Output: true
24-
Explanation: There is a cycle in the linked list, where tail connects to the first node.
25-
26-
Example 3:
27-
Input: head = [1], pos = -1
28-
Output: false
29-
Explanation: There is no cycle in the linked list.
30-
31-
Follow up:
32-
Can you solve it using O(1) (i.e. constant) memory?
33-
*/
348
publicclass_141 {
359

36-
publicstaticclassSolution1 {
37-
publicbooleanhasCycle(ListNodehead) {
38-
Set<ListNode>set =newHashSet();
39-
while (head !=null) {
40-
if (!set.add(head)) {
41-
returntrue;
42-
}
43-
head =head.next;
44-
}
45-
returnfalse;
46-
}
47-
}
48-
49-
publicstaticclassSolution2 {
50-
publicbooleanhasCycle(ListNodehead) {
51-
ListNodeslow =head;
52-
ListNodefast =head;
53-
while (fast !=null &&fast.next !=null) {
54-
fast =fast.next.next;
55-
slow =slow.next;
56-
if (fast ==slow) {
57-
returntrue;
58-
}
59-
}
60-
returnfalse;
61-
}
62-
}
10+
publicstaticclassSolution1 {
11+
publicbooleanhasCycle(ListNodehead) {
12+
Set<ListNode>set =newHashSet();
13+
while (head !=null) {
14+
if (!set.add(head)) {
15+
returntrue;
16+
}
17+
head =head.next;
18+
}
19+
returnfalse;
20+
}
21+
}
22+
23+
publicstaticclassSolution2 {
24+
publicbooleanhasCycle(ListNodehead) {
25+
ListNodeslow =head;
26+
ListNodefast =head;
27+
while (fast !=null &&fast.next !=null) {
28+
fast =fast.next.next;
29+
slow =slow.next;
30+
if (fast ==slow) {
31+
returntrue;
32+
}
33+
}
34+
returnfalse;
35+
}
36+
}
6337
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp