-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0706-design-hashmap.js
More file actions
59 lines (53 loc) · 1.71 KB
/
0706-design-hashmap.js
File metadata and controls
59 lines (53 loc) · 1.71 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
/**
* Design Hashmap
* Time Complexity: O(1)
* Space Complexity: O(M + N)
*/
var MyHashMap = function () {
this.totalBuckets = 1000;
this.hashBuckets = new Array(this.totalBuckets);
for (
let currentBucketIndex = 0;
currentBucketIndex < this.totalBuckets;
currentBucketIndex++
) {
this.hashBuckets[currentBucketIndex] = [];
}
};
MyHashMap.prototype.put = function (keyInput, valueInput) {
let bucketLocation = keyInput % this.totalBuckets;
let targetBucket = this.hashBuckets[bucketLocation];
let initialLength = targetBucket.length;
for (let entryPosition = 0; entryPosition < initialLength; entryPosition++) {
let currentEntry = targetBucket[entryPosition];
if (currentEntry[0] === keyInput) {
currentEntry[1] = valueInput;
return;
}
}
targetBucket.push([keyInput, valueInput]);
};
MyHashMap.prototype.get = function (keyLookup) {
let bucketCoordinate = keyLookup % this.totalBuckets;
let relevantBucket = this.hashBuckets[bucketCoordinate];
let bucketItemCount = relevantBucket.length;
for (let itemPosition = 0; itemPosition < bucketItemCount; itemPosition++) {
let itemEntry = relevantBucket[itemPosition];
if (itemEntry[0] === keyLookup) {
return itemEntry[1];
}
}
return -1;
};
MyHashMap.prototype.remove = function (keyToRemove) {
let bucketPlace = keyToRemove % this.totalBuckets;
let specificBucket = this.hashBuckets[bucketPlace];
let currentBucketSize = specificBucket.length;
for (let elementIndex = 0; elementIndex < currentBucketSize; elementIndex++) {
let bucketElement = specificBucket[elementIndex];
if (bucketElement[0] === keyToRemove) {
specificBucket.splice(elementIndex, 1);
return;
}
}
};