现在的位置: 首页 > 综合 > 正文

【LeetCode笔记】Linked List Cycle

2018年05月24日 ⁄ 综合 ⁄ 共 465字 ⁄ 字号 评论关闭

1. Without using extra space means the space is O(1)

Analysis:

Set a fast runner and a slow runner. The fast runner jumps 2 nodes at one time, and the slow runner jumps 1 nodes at one time. At the beginning, they all at the head node.

If there is a cycle in the linked list, the fast runner will catch up and surpass the slow runner several times.

Let's say the linked list has N nodes, K independent nodes and a cycle of N-K nodes.

The distance each runner has are Dfast and Dslow, and they meet for T times.

so, Dfast = 2*Dslow

      Dfast - Dslow = (N-K)*T

so, Dslow =  (N-K)*T

抱歉!评论已关闭.