forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSample.java
More file actions
70 lines (52 loc) · 1.91 KB
/
Copy pathSample.java
File metadata and controls
70 lines (52 loc) · 1.91 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Time Complexity : O(1)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach
// MyHashSet — a HashSet built from a 2D grid ("hotel with floors and rooms")
//
// Big idea: instead of one giant array of a million booleans, we split each
// key into (floor, room) using % and /, and only build a floor's rooms the
// first time a key actually lands on that floor.
class MyHashSet {
let primaryBuckets = 1000
let secondaryBuckets = 1000
var storage: [[Bool]?]
init() {
storage = [[Bool]?](repeating: nil, count: primaryBuckets)
}
private func getPrimaryHash(_ key: Int) -> Int {
return key % primaryBuckets
}
private func getSecondaryHash(_ key: Int) -> Int {
return key / secondaryBuckets
}
func add(_ key: Int) {
let primaryIndex = getPrimaryHash(key)
if storage[primaryIndex] == nil {
if primaryIndex == 0 {
storage[primaryIndex] = [Bool](repeating: false, count: secondaryBuckets + 1)
} else {
storage[primaryIndex] = [Bool](repeating: false, count: secondaryBuckets)
}
}
let secondaryIndex = getSecondaryHash(key)
storage[primaryIndex]![secondaryIndex] = true
}
func remove(_ key: Int) {
let primaryIndex = getPrimaryHash(key)
guard storage[primaryIndex] != nil else {
return
}
let secondaryIndex = getSecondaryHash(key)
storage[primaryIndex]![secondaryIndex] = false
}
func contains(_ key: Int) -> Bool {
let primaryIndex = getPrimaryHash(key)
guard storage[primaryIndex] != nil else {
return false
}
let secondaryIndex = getSecondaryHash(key)
return storage[primaryIndex]![secondaryIndex]
}
}