Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Resolves: Leetcode 138
Citadel Research Platform team onsite (10/25/19)
Main Techniques:
We first create a copy of the list without assigning value to
random
field. Next, we use a hash table to store the mapping from nodes in the original list to nodes in the copied list. Finally, traverse the original list and the new list in tandem, using the mapping to assign eachrandom
field.The key to improve the space complexity is to use the next field for each node in the original list to record the mapping from the original node to its copy. To avoid losing the structure of the original list, we use the next field in each copied node to point to the successor of its original node.
Ref: EPI p.446
Runtime Complexity Analysis
Brute force: O(n), where n is the number of nodes in the original list
Optimized: O(n)
Space Complexity Analysis
Brute force: O(n), where n is the number of nodes in the original list
Optimized: O(1)
Testing
Performance
Performance Metrics from OJ Platform
Performance Improved Since Last Change
Implementation Notice
In stage 3 of the optimized approach implementation, we have
Here
temp
points to the original list and copied list node in alternative fashion so that we can fix the original listnext
field and the copied listnext
field at the same time in onewhile
loop. Very smart!Implementation Tricks
To Do
EPI p.446 has a robust C++ implementation with usage of
shared_ptr
. However, this implementation clashes with the Leetcode definition. For example, we need to implement new definition ofNode
withshared_ptr<Node_EPI>
as the type forrandom
andnext
field. Along the way, we may need to implement the corresponding test infrastructure. You can check branch https://github.com/xxks-kkk/shuati/tree/138-shared for part of implementation attempt.To Learn
Questions
Language
R"({"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1})"
uses C++11 string literal to easily write string with"
.Failure Attempts