[LeetCode] 142. Linked List Cycle II
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 142. Linked List Cycle II相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/leetcode' title='leetcode'>leetcode
ext corn bsp 涓や釜鎸囬拡 绌洪棿 ctc slow https鍗曢摼琛ㄤ腑鐨勭幆浜屻€傞鎰忔槸缁欎竴涓摼琛紝濡傛灉杩欎釜閾捐〃涓湁鐜紝璇穜eturn鐜殑璧风偣锛涜嫢娌℃湁锛宺eturn null銆傛壘鏄惁鏈夌幆鍙互鍙傜収[LeetCode] 141. Linked List Cycle鐨勮瑙c€傝嚦浜庢€庝箞鎵惧埌鐜殑璧风偣锛屾垜杩欓噷寮曠敤涓€涓潪甯稿ソ鐨勮瑙o紝https://www.cnblogs.com/hiddenfox/p/3408931.html
鍥犱负蹇參鎸囬拡鐨勯€熷害鏄竴涓?姝ヤ竴涓?姝ワ紝鎵€浠ュ綋涓や釜鎸囬拡鐩搁亣鐨勬椂鍊欙紝fast璧拌繃鐨勯暱搴︿竴瀹氭槸slow鐨勪袱鍊嶃€備袱鑰呯浉閬囩殑鍦版柟涓€瀹氭槸鐜殑璧风偣銆傝嚦浜庤瘉鏄庯紝鐩存帴鍙傜収寮曠敤璐淬€?/p>
鏃堕棿O(n)
绌洪棿O(1)
1 /** 2 * @param {ListNode} head 3 * @return {ListNode} 4 */ 5 var detectCycle = function(head) { 6 // corner case 7 if (head === null || head.next === null) { 8 return null; 9 } 10 11 // normal case 12 let slow = head; 13 let fast = head; 14 while (fast !== null && fast.next !== null) { 15 slow = slow.next; 16 fast = fast.next.next; 17 if (fast === slow) { 18 let slow2 = head; 19 while (slow !== slow2) { 20 slow = slow.next; 21 slow2 = slow2.next; 22 } 23 return slow; 24 } 25 } 26 return null; 27 };
以上是关于[LeetCode] 142. Linked List Cycle II的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 141, 142. Linked List Cycle I+II
leetcode-142. Linked List Cycle II
LeetCode142. Linked List Cycle II
LeetCode-142-Linked List Cycle II