LeetCode 之 JavaScript 解答第141題 —— 環形連結串列 I(Linked List Cycle I)

不甘平凡的小鹿發表於2019-04-08

Time:2019/4/7
Title: Linked List Cycle
Difficulty: Easy
Author:小鹿


題目:Linked List Cycle I

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

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.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
複製程式碼

img

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
複製程式碼

img

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
複製程式碼

img

Follow up:

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

Slove:

▉ 演算法思路:

兩種解題思路:

1)雜湊表法:遍歷連結串列,沒遍歷一個節點就要在雜湊表中判斷是否存在該結點,如果存在,則為環;否則,將該結點插入到雜湊表中繼續遍歷。

2)用兩個快慢指標,快指標走兩步,慢指標走一步,如果快指標與慢指標重合了,則檢測的當前連結串列為環;如果當前指標或下一指標為 null ,則連結串列不為環。

▉ 方法一:雜湊表
   /**
        * Definition for singly-linked list.
        * function ListNode(val) {
        *     this.val = val;
        *     this.next = null;
        * }
        */
        /**
        * @param {ListNode} head
        * @return {boolean}
        */

        var hasCycle = function(head) {
            let fast = head;
            let map = new Map();
            while(fast !== null){
                if(map.has(fast)){
                    return true;
                }else{
                    map.set(fast);
                    fast = fast.next;
                }
            }
            return false;
        };

複製程式碼
▉ 方法二:快慢指標
 var hasCycle = function(head) {
     if(head == null || head.next == null){
     	return false;
     }
     let fast = head.next;
     let slow = head;
     while(slow != fast){
         if(fast == null || fast.next == null){
         	return false;
     	 }
         slow = slow.next;
         fast = fast.next.next;
     }
     return true;
 };
複製程式碼
▉ 方法二:快慢指標

這部分程式碼是我自己寫的,和上邊的快慢指標思路相同,執行結果相同,但是當執行在 leetcode 時,就會提示超出時間限制,仔細對比程式碼,我們可以發現,在邏輯順序上還是存在差別的,之所以超出時間限制,是因為程式碼的執行耗時長。

//超出時間限制
var hasCycle = function(head) {
    if(head == null || head.next == null){
    	return false;
    }
    let fast = head.next;
    let slow = head;
    while(fast !== null && fast.next !== null){
        if(slow === fast) return true;
        slow = head.next;
        fast = fast.next.next;
    }
	return false;
};
複製程式碼

歡迎關注我個人公眾號:「一個不甘平凡的碼農」,記錄了自己一路自學程式設計的故事。
LeetCode 其他題目解析,Github:github.com/luxiangqian…

相關文章