题意以及限制条件
-
题目:
-
限制条件:
想到的所有可能解法
-
Ways_1——Two Pointers
- 时间复杂度——O(n);空间复杂度——O(1)
-
Ways_2——HashSet
- 时间复杂度——O(n);空间复杂度——O(n)
对应的代码
- Ways_1
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
ListNode entry = head;
while (entry != slow) {
entry = entry.next;
slow = slow.next;
}
return entry;
}
}
return null;
}
}
- Ways_2
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
HashSet<ListNode> hashset = new HashSet<ListNode>();
while (head != null) {
if (!hashset.add(head))
return head;
head = head.next;
}
return null;
}
}