-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0706-design-hashmap.swift
100 lines (86 loc) · 2.08 KB
/
0706-design-hashmap.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
93
94
95
96
97
98
99
100
/**
* Question Link: https://leetcode.com/problems/design-hashmap/
*/
class Pair {
let key: Int
var val: Int
init(_ key: Int, _ val: Int) {
self.key = key
self.val = val
}
}
class MyHashMap {
var size: Int
var capacity: Int
var map: [Pair?]
init() {
self.size = 0
self.capacity = 10 * 10 * 10 * 10 * 10
self.map = [Pair?](repeating: nil, count: capacity)
}
func hash(_ key: Int) -> Int {
return key % capacity
}
func rehash() {
capacity = 2 * capacity
var newMap = [Pair?](repeating: nil, count: capacity)
let oldMap = map
map = newMap
for pair in oldMap {
if pair != nil {
map.append(pair)
}
}
}
func put(_ key: Int, _ value: Int) {
var index = hash(key)
while true {
if map[index] == nil {
map[index] = Pair(key, value)
size += 1
if size >= capacity / 2 {
rehash()
}
return
} else if map[index]?.key == key {
map[index]?.val = value
return
}
index += 1
index = index % capacity
}
}
func get(_ key: Int) -> Int {
var index = hash(key)
while map[index] != nil {
if map[index]!.key == key {
return map[index]!.val
}
index += 1
index = index % capacity
}
return -1
}
func remove(_ key: Int) {
if get(key) == -1 {
return
}
var index = hash(key)
while true {
if map[index]?.key == key {
map[index] = nil
size -= 1
return
}
index += 1
index = index % capacity
}
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* let obj = MyHashMap()
* obj.put(key, value)
* let ret_2: Int = obj.get(key)
* obj.remove(key)
*/