Junior — Middle
Kas saaks anda näiteid meetoditest, kuidas lahendada kokkupõrkeid, töötades koos hajutustabelitega?
sobes.tech AI
Vastus AI-lt
When working with hash tables, collisions occur when different keys are hashed into the same cell. The main ways to resolve collisions:
-
Chaining method — each cell in the hash table stores a linked list of elements that have fallen into that cell. When a collision occurs, the new element is added to the list.
-
Open addressing — in case of collision, the next free cell is searched according to a certain rule (linear probing, quadratic probing, double hashing).
Example of chaining method:
class HashTable {
var buckets: [[(key: String, value: Int)]]
init(size: Int) {
buckets = Array(repeating: [], count: size)
}
func hash(_ key: String) -> Int {
return abs(key.hashValue) % buckets.count
}
func insert(key: String, value: Int) {
let index = hash(key)
buckets[index].append((key, value))
}
}
Therefore, the choice of method depends on performance and memory requirements.