Leetcode 141. Linked List Cycle

problems:
https://leetcode.com/problems/linked-list-cycle/description/
https://leetcode.com/problems/linked-list-cycle-ii/description/
https://leetcode.com/problems/find-the-duplicate-number/description/
discuss:
https://discuss.leetcode.com/topic/2975/o-n-solution-by-using-two-pointers-without-change-anything
https://discuss.leetcode.com/topic/25580/two-solutions-with-explanation-o-nlog-n-and-o-n-time-o-1-space-without-changing-the-input-array
reference:
http://keithschwarz.com/interesting/code/?dir=find-duplicate

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

碰到很有意思的一组题目,记录一下。

不限定空间的话,那么O(n)记忆一下,就解出来了。
但是要O(1)的空间的话,就没什么头绪。
翻了下discuss,发现这题很有意思。

用快慢指针的想法,假如存在cycle,那么必定在某点相遇

// initial-state: fast = slow = head
while (fast->next != nullptr && fast->next->next != nullptr) {
    slow = slow->next;
    fast = fast->next;
    if (slow == fast) return true;
}
return false;

进一步,怎么确定cycle的入口entry呢?
假设相遇在k处,入口在s处,相遇点距离入口m处,cycle长度为r,
那么slow走了k,fast走了2k

  |<-          k           ->|
  |<-   s    ->|<-    m    ->|
head ------- entry --->---meeting--->---
               ^                       |
               |                       v
               ------------<------------

k + nr = 2k
=> k = nr
=> k = (n-1)r + r
=> k-m = (n-1)r + r-m
=> s = (n-1)r + r-m
=> s = r-m

意味着相遇点在走r-m=s步就回到了入口处

// initial-state: fast = slow = entry = head
while (fast->next != nullptr && fast->next->next != nullptr) {
    slow = slow->next;
    fast = fast->next;
    if (slow == fast) {
        while (entry != slow) {
            entry = entry->next;
            slow = slow->next;
        }
        return entry;
    }
}
return nullptr;

另外在看看这题 287. Find the Duplicate Number

https://leetcode.com/problems/find-the-duplicate-number/description/

翻翻这题的discuss,也可以用类似的思想去找到这个Duplicate Number,因为相同的数不同的index在这个数组中构成了一个cycle
这类问题可以归纳为cycle detection

a well-studied problem in computer science called cycle detection.
http://keithschwarz.com/interesting/code/?dir=find-duplicate

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值