牛客網高頻演算法題系列-BM6-判斷連結串列中是否有環
阿新 • • 發佈:2022-05-30
牛客網高頻演算法題系列-BM6-判斷連結串列中是否有環
題目描述
判斷給定的連結串列中是否有環。如果有環則返回true,否則返回false。
原題目見:BM6 判斷連結串列中是否有環
解法一:雙指標法
使用兩個指標,fast 與 slow。它們起始都位於連結串列的頭部。隨後,slow 指標每次向後移動一個位置,而fast 指標向後移動兩個位置。如果連結串列中存在環,則 fast 指標最終將再次與 slow 指標在環中相遇。
原理可參考:雙指標演算法原理詳解
解法二:雜湊法
使用HashSet記錄連結串列中的結點,然後遍歷連結串列結點:
- 如果連結串列中的結點在雜湊表中出現過,說明連結串列有環,直接返回true
- 如果連結串列中的結點沒有在雜湊表中出現過,則將當前結點新增到雜湊表中,然後判斷下一個結點
最後,如果沒有重複節點,則說明無環,返回false。
程式碼
import java.util.HashSet; public class Bm006 { /** * 雙指標 * * @param head * @return */ public static boolean hasCycle(ListNode head) { ListNode fast = head, slow = head; while (fast != null && fast.next != null) { // 快指標每次走2步,慢指標每次走1步 fast = fast.next.next; slow = slow.next; if (fast == slow) { // 快慢指標相遇,說明連結串列中有環 return true; } } // 快慢指標沒有相遇,說明無環 return false; } /** * 雜湊法 * * @param head * @return */ public static boolean hasCycle2(ListNode head) { // 用來記錄連結串列中未重複的結點 HashSet<ListNode> nodes = new HashSet<>(); while (head != null) { // 如果連結串列中的結點已經出現過,說明有環,返回true if (nodes.contains(head)) { return true; } nodes.add(head); head = head.next; } // 如果沒有重複節點,則說明無環,返回false。 return false; } public static void main(String[] args) { /** * 測試用例連結串列結構為有環 * testCaseCycle: 3 -> 2 -> 0 -> -4 * ^ | * ------------ */ ListNode head = ListNode.testCaseCycle(); /** * 測試用例,期望輸出: true */ System.out.println(hasCycle(head)); System.out.println(hasCycle2(head)); } }
\(1.01^{365} ≈ 37.7834343329\)
\(0.99^{365} ≈ 0.02551796445\)
相信堅持的力量!