为什么我达到了时间限制!? LeetCode 链表循环(已解决,但需要解释!)

问题描述 投票:0回答:1

我正在 leetcode 上解决这个问题(https://leetcode.com/problems/linked-list-cycle/description/),而我原来的解决方案超出了时间限制(示例 A)。我最终能够通过更改两行代码来使解决方案足够快,并且该解决方案被接受并且性能更高。 为什么示例 B示例 A更快?为什么变量赋值比使用原始对象更快/性能更高?

我改变了这个...

示例 A(失败的解决方案)

var hasCycle = function(head) {
// some code ...
   let fastPointer = null;

   fastPointer = head?.next?.next || null;
// ...
}

对此...

示例 B(工作解决方案)

var hasCycle = function(head) {
// some code ...
   let fastPointer = head;

   fastPointer = fastPointer?.next?.next || null;
// ...
}

这是两种解决方案的完整代码...

示例 A(失败的解决方案)....

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
   // create a fast pointer
   let fastPointer = null;

   // create a while loop that lasts for as long as head exists

   while (head) {
    // move fast pointer over by 2
    fastPointer = head?.next?.next || null;

    // if fastpointer is null, this indicates that there is no cycle so return false
    if (fastPointer === null) return false;

    // compare fastPointer to the slow pointer, if they are ever equal to the same node then the list contains a cycle.
    if (fastPointer === head) return true;

    // move head by 1
    head = head.next;


   }




   // if the while loop ends, it indicates the there is no cycle so return false

   return false;
};   

示例 B(工作解决方案)...

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
   // create a fast pointer
   let fastPointer = head;

   // create a while loop that lasts for as long as head exists

   while (head) {
    // move fast pointer over by 2 
    // !!!CHANGE HAPPENED HERE and solution worked!!!!
    fastPointer = fastPointer?.next?.next || null;

    // if fastpointer is null, this indicates that there is no cycle so return false
    if (fastPointer === null) return false;

    // compare fastPointer to the slow pointer, if they are ever equal to the same node then the list contains a cycle.
    if (fastPointer === head) return true;

    // move head by 1
    head = head.next;


   }


   // if the while loop ends, it indicates the there is no cycle so return false

   return false;
};   
javascript performance data-structures ecmascript-6 singly-linked-list
1个回答
0
投票

在您定义的第一个解决方案中

let fastPointer = null;

然后你做这个:

fastPointer = fastPointer?.next?.next || null;

这意味着您正在尝试重新分配变量,并且该变量已经为空,这意味着

fastPointer = null?.next?.next || null;

在第一个可选链中它已经为空 这意味着这个条件:

if (fastPointer === null)

为 true 并且会返回 false,即使我有一个循环并且代码不会完成执行

所以基本上这不是时间超过“这立即返回错误......

© www.soinside.com 2019 - 2024. All rights reserved.