注:此博客不再更新,所有最新文章將發表在個人獨立博客limengting.site。分享技術,記錄生活,歡迎大家關注
題目描述
一個鏈表中包含環,請找出該鏈表的環的入口結點。
方法一:空間複雜度O(n)
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
import java.util.HashSet;
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
// 1、head作爲key放入hashset,只有key,沒有value,空間複雜度O(n)
if (pHead == null) return null;
HashSet<ListNode> set = new HashSet<>();
while (pHead != null) {
if (!set.add(pHead)) {
return pHead;
}
pHead = pHead.next;
}
return null;
}
}
方法二:空間複雜度O(1)
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
// 2、不使用輔助空間
// 快指針一次走兩步,慢指針一次走一步,如果快指針遇到空則返回無環
// 如果有環則快指針和慢指針一定會相遇,相遇後快指針回到開頭,以後快指針和慢指針都一次走一步,相遇處即爲入環節點
if (pHead == null || pHead.next == null) return null;
ListNode fast = pHead.next.next;
ListNode slow = pHead.next;
while (fast != slow) {
if (fast == null || fast.next == null) {
return null;
}
slow = slow.next;
fast = fast.next.next;
}
fast = pHead;
while (fast != slow) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
}