Leetcode刷題Java142. 環形鏈表 II

給定一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 null。

爲了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。

說明:不允許修改給定的鏈表。

示例 1:

輸入:head = [3,2,0,-4], pos = 1
輸出:tail connects to node index 1
解釋:鏈表中有一個環,其尾部連接到第二個節點。

示例 2:

輸入:head = [1,2], pos = 0
輸出:tail connects to node index 0
解釋:鏈表中有一個環,其尾部連接到第一個節點。

示例 3:

輸入:head = [1], pos = -1
輸出:no cycle
解釋:鏈表中沒有環。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/linked-list-cycle-ii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

public class Solution {
        public ListNode detectCycle(ListNode head) {
//            return detectCycleI(head);
            return detectCycleII(head);
        }

        //方法二:使用快慢指針,慢指針移動1步,快指針移動2步
        //首先判斷是否有環,沒有直接返回null,有則獲取快慢指針的相遇點
        //假設head指針到入口處的距離爲F,相遇點到入口處距離爲a,相遇點到入口處的剩下距離爲b
        //快指針移動的距離是慢指針的2倍
        //2(F + a) = F + a + b + a -->F=b
        //得到F=b,也就是說指針從head節點出發和從相遇點出發最終會在入口處相遇
        private ListNode detectCycleII(ListNode head) {
            if (head == null) return null;
            ListNode meet = getMeetPoint(head);
            if (meet == null) return null;
            while (meet != head) {
                meet = meet.next;
                head = head.next;
            }
            return head;
        }

        private ListNode getMeetPoint(ListNode head) {
            ListNode slow = head;
            ListNode fast = head;
            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
                if (slow == fast) {
                    return slow;
                }
            }
            return null;
        }

        //方法一:暴力法
        //使用HashSet緩存鏈表
        private ListNode detectCycleI(ListNode head) {
            Set<ListNode> set = new LinkedHashSet<>();
            while (head != null) {
                if (set.contains(head)) {
                    return head;
                }
                set.add(head);
                head = head.next;
            }
            return null;
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章