Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
copy-list-with-random-pointer.py 2.23 KB
一键复制 编辑 原始数据 按行查看 历史
Sanghee Kim 提交于 2019-01-12 23:08 +08:00 . add a solution and update doc
# Time: O(n)
# Space: O(1)
class RandomListNode(object):
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution(object):
# @param head, a RandomListNode
# @return a RandomListNode
def copyRandomList(self, head):
# copy and combine copied list with original list
current = head
while current:
copied = RandomListNode(current.label)
copied.next = current.next
current.next = copied
current = copied.next
# update random node in copied list
current = head
while current:
if current.random:
current.next.random = current.random.next
current = current.next.next
# split copied list from combined one
dummy = RandomListNode(0)
copied_current, current = dummy, head
while current:
copied_current.next = current.next
current.next = current.next.next
copied_current, current = copied_current.next, current.next
return dummy.next
# Time: O(n)
# Space: O(n)
class Solution2(object):
# @param head, a RandomListNode
# @return a RandomListNode
def copyRandomList(self, head):
dummy = RandomListNode(0)
current, prev, copies = head, dummy, {}
while current:
copied = RandomListNode(current.label)
copies[current] = copied
prev.next = copied
prev, current = prev.next, current.next
current = head
while current:
if current.random:
copies[current].random = copies[current.random]
current = current.next
return dummy.next
# time: O(n)
# space: O(n)
from collections import defaultdict
class Solution3(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
clone = defaultdict(lambda: RandomListNode(0))
clone[None] = None
cur = head
while cur:
clone[cur].label = cur.label
clone[cur].next = clone[cur.next]
clone[cur].random = clone[cur.random]
cur = cur.next
return clone[head]
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助