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. 復制代碼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)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c#winform pictureBox
- 下一篇: 闪回技术