-
Notifications
You must be signed in to change notification settings - Fork 0
/
138.swift
49 lines (41 loc) · 991 Bytes
/
138.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//
// 138.swift
//
//
// Created by Sebastian on 8/21/24.
//
import Foundation
public class Node {
public var val: Int
public var next: Node?
public var random: Node?
public init(_ val: Int) {
self.val = val
self.next = nil
self.random = nil
}
}
extension Node: Hashable, Equatable {
public func hash(into hasher: inout Hasher) {
hasher.combine(val)
hasher.combine(ObjectIdentifier(self))
}
public static func ==(lhs: Node, rhs: Node) -> Bool {
return lhs === rhs
}
}
class Solution {
var cachedNodes = [Node : Node]()
func copyRandomList(_ head: Node?) -> Node? {
guard let head = head else {
return nil
}
if cachedNodes[head] == nil {
var newHead = Node(head.val)
cachedNodes[head] = newHead
newHead.next = copyRandomList(head.next)
newHead.random = copyRandomList(head.random)
}
return cachedNodes[head]
}
}