-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathHashSet.swift
More file actions
72 lines (64 loc) Β· 1.63 KB
/
Copy pathHashSet.swift
File metadata and controls
72 lines (64 loc) Β· 1.63 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
//
// HashSet.swift
// Algorithm Solutions In Swift
//
// Created by Boudhayan Biswas on 23/07/23.
//
import Foundation
fileprivate class Node {
var next: Node?
var key: Int
init(key: Int) {
self.key = key
}
}
fileprivate class MyHashSet {
var array: [Node?] = Array(repeating: nil, count: 10000)
func hash(key: Int) -> Int {
key % array.count
}
func add(_ key: Int) {
let hash = hash(key: key)
guard let root = array[hash] else {
array[hash] = Node(key: key); return
}
var cur: Node? = root
while cur != nil {
if cur!.key == key {return}
if cur!.next == nil {break}
cur = cur!.next
}
cur!.next = Node(key: key)
}
func remove(_ key: Int) {
let hash = hash(key: key)
guard let root = array[hash] else { return }
if root.key == key {
array[hash] = root.next
}
var cur: Node? = root
while cur!.next != nil {
if cur!.next!.key == key {
cur!.next = cur!.next!.next; return
}
cur = cur!.next
}
}
func contains(_ key: Int) -> Bool {
let hash = hash(key: key)
guard let root = array[hash] else { return false}
var cur: Node? = root
while cur != nil {
if cur!.key == key {return true}
cur = cur!.next
}
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)
*/