版权声明:三和小钢炮 https://blog.csdn.net/fwx426328/article/details/82316477
javaScript数据结构之HashMap
01 HashMap
原理是用一个散列表,分出哈希值,再由每个位置创建一个LinkList
02 hashMap原理
我们用一个数组,来承装键值对。
我们可以这样,实现一个哈希算法,来计算承装的下标。
function HashMap() {
var _list = [];
/*hash算法,用可以计算出数组的下标*/
function loseloseHashCode(key) {
// 我们简单模拟下
return key.charCodeAt() % 100;
};
this.put = function(key, value) {
var position = loseloseHashCode(key);
_list[position] = value;
};
this.get = function(key) {
var position = loseloseHashCode(key);
return _list[position];
}
}
var h = new HashMap();
h.put('a', 'a');
h.put('b', 'b');
console.log(h.get('a'));
上面的算法是存在问题的,因为hash算法没有保障hashCode的唯一性。那么冲突就是难免的。这就是— 哈希冲突。
当然,一个好的哈希算法应该尽量避免哈希冲突。
解决这个问题,我们需要在数组的位置创建一个链表,然后每次在链表里面添加值。
如下图所展示:
key值 | hash值 | 链表 |
---|---|---|
猴子1、猴子2、猴子3 | 0 | ['孙悟空', '六耳猕猴', '通背猿猴'] |
猪 | 5 | ['猪八戒'] |
和尚1、和尚2 | 30 | ['唐僧', '如来'] |
03 实现一个hashMap
这里要依赖linkList
function HashMap() {
var _table = [];
//装元素的类
var ValuePair = function(key, value) {
this.key = key;
this.value = value;
};
this.toString = function () {
return '[' + this.key + '-' + this.value + ']';
};
/* hash算法 */
var loseloseHashCode = function (key) {
var hash = 0;
for (var i = 0; i < key.length; i++) {
hash += key.charCodeAt(i);
}
return hash % 37;
};
this.put = function (key, value) {
var position = loseloseHashCode(key);
if (_table[position] == undefined) {
_table[position] = new Linklist();
}
_table[position].add(new ValuePair(key, value));
};
this.get = function (key) {
var position = loseloseHashCode(key);
if (_table[position] != undefined) {
var current = _table[position].head;
while (current.next) {
if (current.data.key == key) {
return current.data.value;
}
current = c
urrent.next;
}
if (current.data.key == key) {
return current.data.value;
}
}
return _table[loseloseHashCode(key)];
};
this.remove = function(key) {
var position = loseloseHashCode(key);
if (_table[position] != undefined) {
var current = _table[position].head;
var index = 0;
while (current.next) {
if (current.data.key == key) {
_table[position].remove(index);
if (_table[position].length == 0) {
_table[position] = undefined;
}
}
current = current.next;
index++;
}
if (current.data.key == key) {
_table[position].remove(index);
if (_table[position].length == 0) {
_table[position] = undefined;
}
}
}
}
};
map.put("b", "李四");
map.remove("a");
console.log(map.get("a"));
console.log(map.get("b"));
04 哈希算法
由上可以看出:
如果没有哈希冲突,那么HashMap的插入和获取的时间复杂度基本是 O(1);
所以一个表现良好的哈希算法特别重要。
05 对象
写了这么多,我们会发现,最终居然回到了key和val的问题上。
js中,对象默认就具有如此属性。
也就是说—js对象就是HashMap实现的。
所以,我们以后使用对象的时候就可以当做map使用。