LeetCode 之 JavaScript 解答第141題 —— 環形鏈表 I(Linked List Cycle I)


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


題目:Linked List Cycle I

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

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.node

Example 1:git

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:github

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?bash

Slove:

▉ 算法思路:

兩種解題思路:ui

1)哈希表法:遍歷鏈表,沒遍歷一個節點就要在哈希表中判斷是否存在該結點,若是存在,則爲環;不然,將該結點插入到哈希表中繼續遍歷。this

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 倉庫,能夠向 me 提交您其餘語言的代碼。在倉庫上堅持和小夥伴們一塊兒打卡,共同完善咱們的開源小倉庫! Github:https://github.com/luxiangqiang/JS-LeetCode 歡迎關注我我的公衆號:「一個不甘平凡的碼農」,記錄了本身一路自學編程的故事。
相關文章
相關標籤/搜索