[Question]: Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet
class:
void add(key)
Inserts the valuekey
into the HashSet.bool contains(key)
Returns whether the valuekey
exists in the HashSet or not.void remove(key)
Removes the valuekey
in the HashSet. Ifkey
does not exist in the HashSet, do nothing.
class MyHashSet {
private var data = [Bool?](repeating: false, count: 1000001)
init() {}
func add(_ key: Int) { data[key] = true }
func remove(_ key: Int) { data[key] = nil }
func contains(_ key: Int) -> Bool { data[key] ?? false }
}
// Bitwise Solution: --
class MyHashSet2 {
private var bits = [Int](repeating: 0, count: 1000001) // 15_626 = 1_000_000 / 64 + 1
func add(_ key: Int) { bits[key>>6] |= 1<<(key&63) }
func remove(_ key: Int) { bits[key>>6] &= ~(1<<(key&63)) }
func contains(_ key: Int) -> Bool { bits[key>>6] & 1<<(key&63) != 0 }
}