题目描述
1. 双指针
代码实现
/**
* @Classname Solution
* @Description TODO
* @Date 2019/12/23 11:27
* @Author SonnSei
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
if(pHead == null || pHead.next==null)return null;
ListNode fast = pHead;
ListNode slow = pHead;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
if(fast == slow)
break;
}
if(fast!=slow)return null;
fast = pHead;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
复杂度分析
时间复杂度:
O
(
n
)
{O(n)}
O(n)
空间复杂度:
O
(
1
)
{O(1)}
O(1)
2. 利用Set
代码实现
/**
* @Classname Solution2
* @Description TODO
* @Date 2019/12/27 9:33
* @Author SonnSei
*/
public class Solution2 {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
Set<ListNode> set = new HashSet<>();
ListNode cur = pHead;
while (cur != null) {
if (set.contains(cur)) {
return cur;
}
set.add(cur);
cur = cur.next;
}
return null;
}
}
复杂度分析
时间复杂度:
O
(
n
)
{O(n)}
O(n)
空间复杂度:
O
(
n
)
{O(n)}
O(n)