|
5 | 5 | import java.util.HashSet;
|
6 | 6 | import java.util.Set;
|
7 | 7 |
|
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 |
| - */ |
34 | 8 | public class _141 {
|
35 | 9 |
|
36 |
| - public static class Solution1 { |
37 |
| - public boolean hasCycle(ListNode head) { |
38 |
| - Set<ListNode> set = new HashSet(); |
39 |
| - while (head != null) { |
40 |
| - if (!set.add(head)) { |
41 |
| - return true; |
42 |
| - } |
43 |
| - head = head.next; |
44 |
| - } |
45 |
| - return false; |
46 |
| - } |
47 |
| - } |
48 |
| - |
49 |
| - public static class Solution2 { |
50 |
| - public boolean hasCycle(ListNode head) { |
51 |
| - ListNode slow = head; |
52 |
| - ListNode fast = head; |
53 |
| - while (fast != null && fast.next != null) { |
54 |
| - fast = fast.next.next; |
55 |
| - slow = slow.next; |
56 |
| - if (fast == slow) { |
57 |
| - return true; |
58 |
| - } |
59 |
| - } |
60 |
| - return false; |
61 |
| - } |
62 |
| - } |
| 10 | + public static class Solution1 { |
| 11 | + public boolean hasCycle(ListNode head) { |
| 12 | + Set<ListNode> set = new HashSet(); |
| 13 | + while (head != null) { |
| 14 | + if (!set.add(head)) { |
| 15 | + return true; |
| 16 | + } |
| 17 | + head = head.next; |
| 18 | + } |
| 19 | + return false; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + public static class Solution2 { |
| 24 | + public boolean hasCycle(ListNode head) { |
| 25 | + ListNode slow = head; |
| 26 | + ListNode fast = head; |
| 27 | + while (fast != null && fast.next != null) { |
| 28 | + fast = fast.next.next; |
| 29 | + slow = slow.next; |
| 30 | + if (fast == slow) { |
| 31 | + return true; |
| 32 | + } |
| 33 | + } |
| 34 | + return false; |
| 35 | + } |
| 36 | + } |
63 | 37 | }
|
0 commit comments