javascript
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. 復(fù)制代碼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. 復(fù)制代碼Example 3:
Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list. 復(fù)制代碼Follow up:
Can you solve it using O(1) (i.e. constant) memory?
Slove:
▉ 算法思路:
兩種解題思路:
1)哈希表法:遍歷鏈表,沒(méi)遍歷一個(gè)節(jié)點(diǎn)就要在哈希表中判斷是否存在該結(jié)點(diǎn),如果存在,則為環(huán);否則,將該結(jié)點(diǎn)插入到哈希表中繼續(xù)遍歷。
2)用兩個(gè)快慢指針,快指針走兩步,慢指針走一步,如果快指針與慢指針重合了,則檢測(cè)的當(dāng)前鏈表為環(huán);如果當(dāng)前指針或下一指針為 null ,則鏈表不為環(huán)。
▉ 方法一:哈希表
/*** 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;};復(fù)制代碼▉ 方法二:快慢指針
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;}; 復(fù)制代碼▉ 方法二:快慢指針
這部分代碼是我自己寫(xiě)的,和上邊的快慢指針?biāo)悸废嗤?#xff0c;運(yùn)行結(jié)果相同,但是當(dāng)運(yùn)行在 leetcode 時(shí),就會(huì)提示超出時(shí)間限制,仔細(xì)對(duì)比代碼,我們可以發(fā)現(xiàn),在邏輯順序上還是存在差別的,之所以超出時(shí)間限制,是因?yàn)榇a的運(yùn)行耗時(shí)長(zhǎng)。
//超出時(shí)間限制 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; }; 復(fù)制代碼歡迎一起加入到 LeetCode 開(kāi)源 Github 倉(cāng)庫(kù),可以向 me 提交您其他語(yǔ)言的代碼。在倉(cāng)庫(kù)上堅(jiān)持和小伙伴們一起打卡,共同完善我們的開(kāi)源小倉(cāng)庫(kù)! Github:https://github.com/luxiangqiang/JS-LeetCode
歡迎關(guān)注我個(gè)人公眾號(hào):「一個(gè)不甘平凡的碼農(nóng)」,記錄了自己一路自學(xué)編程的故事。
總結(jié)
以上是生活随笔為你收集整理的LeetCode 之 JavaScript 解答第141题 —— 环形链表 I(Linked List Cycle I)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c#winform pictureBox
- 下一篇: 1.10-SpringMVC直接访问WE