Skip to content

Commit af7f1f8

Browse files
committed
Add a solution to Snapshot Array
1 parent 78e53ed commit af7f1f8

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Design/SnapshotArray.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/snapshot-array/
3+
* Primary idea: Use the dictionary to dictionary to hold snapshot id to array data if necessary
4+
*
5+
* Time Complexity: O(1), Space Complexity: O(n)
6+
*
7+
*/
8+
9+
class SnapshotArray {
10+
11+
private var snapshotArrayMap: [Int: [Int: Int]]
12+
private var count = 0
13+
private var array = [Int: Int]()
14+
15+
init(_ length: Int) {
16+
snapshotArrayMap = [Int: [Int: Int]]()
17+
}
18+
19+
func set(_ index: Int, _ val: Int) {
20+
array[index] = val
21+
}
22+
23+
func snap() -> Int {
24+
snapshotArrayMap[count] = array
25+
count += 1
26+
27+
return count - 1
28+
}
29+
30+
func get(_ index: Int, _ snap_id: Int) -> Int {
31+
return snapshotArrayMap[snap_id]?[index] ?? 0
32+
}
33+
}

0 commit comments

Comments
 (0)