-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathHashMap.swift
More file actions
99 lines (88 loc) Β· 2.32 KB
/
Copy pathHashMap.swift
File metadata and controls
99 lines (88 loc) Β· 2.32 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
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
//
// HashMap.swift
// Algorithm Solutions In Swift
//
// Created by Boudhayan Biswas on 23/07/23.
//
import Foundation
fileprivate class MyHashMap {
class Node {
var key: Int
var value: Int
var next: Node?
init(key: Int, value: Int, next: Node? = nil) {
self.key = key
self.value = value
self.next = next
}
}
private var container: [Node?]
private var keyRange: Int
init() {
self.keyRange = 2970
self.container = [Node?](repeating: nil, count: self.keyRange)
}
private func hash(_ key: Int) -> Int {
return key%keyRange
}
func put(_ key: Int, _ value: Int) {
let idx = hash(key)
guard container[idx] != nil else {
container[idx] = Node(key: key, value: value)
return
}
var current: Node? = container[idx]
while let node = current {
if node.key == key {
node.value = value
return
}
if node.next == nil {
break
}
current = node.next
}
current?.next = Node(key: key, value: value)
}
func get(_ key: Int) -> Int {
let idx = hash(key)
guard container[idx] != nil else {
return -1
}
var current: Node? = container[idx]
while let node = current {
if node.key == key {
return node.value
}
current = node.next
}
return -1
}
func remove(_ key: Int) {
let idx = hash(key)
guard container[idx] != nil else {
return
}
if let node = container[idx], node.key == key {
container[idx] = node.next
return
}
var previous: Node? = container[idx]
var current: Node? = container[idx]?.next
while let node = current {
if node.key == key {
previous?.next = node.next
return
}
previous = current
current = current?.next
}
}
}
/**
* 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)
*/