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