1. 程式人生 > >LeetCode:141,Linked List Cycle(判斷連結串列中是否有環)

LeetCode:141,Linked List Cycle(判斷連結串列中是否有環)

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space? 


方法1(利用hash表的方式):

public boolean hasCycle(ListNode head) {
    Set<ListNode> nodesSeen = new HashSet<>();
    while (head != null) {
        if (nodesSeen.contains(head)) {
            return true;
        } else {
            nodesSeen.add(head);
        }
        head = head.next;
    }
    return false;
}

時間複雜度:O(n)

空間複雜度:O(n) 


方法2(利用快慢指標方式):

public boolean hasCycle(ListNode head) {
    if (head == null || head.next == null) {
        return false;
    }
    ListNode slow = head;
    ListNode fast = head.next;
    while (slow != fast) {
        if (fast == null || fast.next == null) {
            return false;
        }
        slow = slow.next;
        fast = fast.next.next;
    }
    return true;
}

時間複雜度:O(n)

空間複雜度O(1)