日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

LeetCode 之 JavaScript 解答第141题 —— 环形链表 I(Linked List Cycle I)

發布時間:2024/1/17 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 之 JavaScript 解答第141题 —— 环形链表 I(Linked List Cycle I) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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. 復制代碼

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. 復制代碼

Example 3:

Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list. 復制代碼

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 倉庫,可以向 me 提交您其他語言的代碼。在倉庫上堅持和小伙伴們一起打卡,共同完善我們的開源小倉庫! Github:https://github.com/luxiangqiang/JS-LeetCode
歡迎關注我個人公眾號:「一個不甘平凡的碼農」,記錄了自己一路自學編程的故事。

總結

以上是生活随笔為你收集整理的LeetCode 之 JavaScript 解答第141题 —— 环形链表 I(Linked List Cycle I)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。