-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0705-design-hashset.swift
92 lines (81 loc) · 1.94 KB
/
0705-design-hashset.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* Question Link: https://leetcode.com/problems/design-hashset/
*/
class MyHashSet {
var map: [Int?]
var size: Int
var capacity: Int
init() {
self.map = [Int?](repeating: nil, count: 10 * 10 * 10 * 10 * 10)
self.size = 0
self.capacity = 10 * 10 * 10 * 10 * 10
}
func hash(_ key: Int) -> Int {
return key % capacity
}
func rehash() {
capacity = 2 * capacity
let oldMap = map
var newMap = [Int?]()
for i in 0..<capacity {
newMap.append(nil)
}
map = newMap
size = 0
for i in 0..<oldMap.count {
if oldMap[i] != nil {
add(oldMap[i]!)
}
}
}
func add(_ key: Int) {
var index = hash(key)
while true {
if map[index] == nil {
map[index] = key
size += 1
if size >= capacity / 2 {
rehash()
}
return
} else if map[index] == key {
return
}
index += 1
index = index % capacity
}
}
func remove(_ key: Int) {
if !contains(key) {
return
}
var index = hash(key)
while true {
if map[index] == key {
map[index] = nil
size -= 1
return
}
index += 1
index = index % capacity
}
}
func contains(_ key: Int) -> Bool {
var index = hash(key)
while map[index] != nil {
if map[index] == key {
return true
}
index += 1
index = index % capacity
}
return false
}
}
/**
* Your MyHashSet object will be instantiated and called as such:
* let obj = MyHashSet()
* obj.add(key)
* obj.remove(key)
* let ret_3: Bool = obj.contains(key)
*/