detectCycle

https://leetcode.com/problems/linked-list-cycle-ii/
給定一個(gè)鏈表,判斷是否有環(huán),并且返回環(huán)開始的那個(gè)ListNode

  • 思路1
    HashSet存下來每一個(gè)走過的路,一直遍歷,當(dāng)發(fā)現(xiàn)set中有,則表明有環(huán)
    public ListNode detectCycle(ListNode head) {
      Set<ListNode> se = new HashSet<ListNode>();
        ListNode tmp = head;
        se.add(tmp);
        while (tmp != null && tmp.next != null) {
            tmp = tmp.next;
            if (se.contains(tmp)) {
                return tmp;
            }
            se.add(tmp);
        }
        return null;
    }
  • 思路2
    1.快慢指針,先確定有換
    2.fast不變,把slow指針再?gòu)念^開始,fast和slow同時(shí)走,再相交的地方就是環(huán)的起點(diǎn)

參考:https://www.cnblogs.com/grandyang/p/4137302.html

        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                break;
            }
        }
        if (fast == null || fast.next == null) {
            return null;
        }

        slow = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容