LeetCode 141:環形鏈表 Linked List Cycle

給定一個鏈表,判斷鏈表中是否有環。java

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

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

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.數據結構

示例 1:性能

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

img

示例 2:學習

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

img

示例 3:3d

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

img

進階:指針

你能用 O(1)(即,常量)內存解決此問題嗎?code

Follow up:對象

Can you solve it using O(1) (i.e. constant) memory?

解題思路:

​ 從頭節點向後遍歷整個鏈表只要遍歷到節點爲 null ,就證實不是環形,而若是遍歷到一個節點的地址以前存在過就證實有環。

一、哈希表:

解決重複問題最容易想到的數據結構就是哈希表,哈希表添加節點時只要發現節點已經存在了,證實就有環形鏈表。而且哈希表查找和插入複雜度都爲O(1),可是空間複雜度會隨着原鏈表長度而增大:O(n),總的來講:

  • 時間複雜度:O(n),雖然哈希表的查找和添加操做的時間複雜度是 O(1) ,可是先須要遍歷鏈表而後插入,遍歷的複雜度是O(n)
  • 空間複雜度:O(n),最多須要保存鏈表的 n個節點

二、雙指針:

這道題就如同小學跑步問題,假設有兩我的(雙指針)一個快一個慢,不停地向前跑,若是跑得快的那個最後到終點了(遇到空節點 null),就證實是直線跑道(沒有環形鏈表)。

若是是存在環形跑道(環形鏈表):兩我的一塊兒跑步(雙指針)一個快一個慢,那麼這兩我的由於速度不一樣,在環形跑道里跑得快的那我的必定會追上慢的。即兩個指針相遇了,證實存在環形鏈表。

空間複雜度爲O(1),即進階要求的常量內存。

哈希表解題:

Java:

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null) return false;//若是是空鏈表直接返回
        Set<ListNode> nodeSet = new HashSet<>();//構造哈希表
        while (head.next != null) {//鏈表下一個不爲空
            if (nodeSet.contains(head)) return true;//哈希表包含該節點則存在環形鏈表
            nodeSet.add(head);//加入節點
            head = head.next;//下移一位
        }
        return false;
    }
}

Python:

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head is None:
            return False
        hashSet=set()#構造集合
        while(head.next is not None):
            if head in hashSet:#是否已存在
                return True
            hashSet.add(head)
            head=head.next
        return False

雙指針解題:

Java:

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {//快指針及其下一位是否爲空
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {//若是相遇,存在環形鏈表
                return true;
            }
        }
        return false;
    }
}

Python:

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head is None or head.next is None:
            return False
        slow, fast = head, head
        while fast is not None and fast.next is not None:
            slow, fast = slow.next, fast.next.next
            if slow == fast:
                return True
        return False

擴展:

python 中is 與 == 區別 :

is 用於判斷兩個變量引用對象(即內存地址)是否爲同一個, == 用於判斷引用變量的值是否相等。

而Python出於對性能的考慮,不可變對象、同一代碼塊中的對象、值相同的對象,都不會重複建立,而是直接引用已經存在的對象。

歡迎關注公衆號:愛寫bug,一塊兒學習。

愛寫bug.png

相關文章
相關標籤/搜索