JavaScript数据结构——字典和散列表的实现
- 时间:
- 浏览:0
在前一篇文章中,亲戚亲戚我们介绍了如何在JavaScript中实现集合。字典和集合的主要区别就在于,集合中数据是以[值,值]的形式保存的,亲戚亲戚我们只关心值本身;而在字典和散列表中数据是以[键,值]的形式保存的,键只能重复,亲戚亲戚我们不仅关心键,也关心键所对应的值。
亲戚亲戚我们也都只能把字典称之为映射表。或者字典和集合很例如,亲戚亲戚我们都只能在前一篇文章中的集合类Set的基础上来实现亲戚亲戚我们的字典类Dictionary。与Set类例如,ES6的原生Map类或者实现了字典的完整版功能,稍后亲戚亲戚我们会介绍它的用法。
下面是亲戚亲戚我们的Dictionary字典类的实现代码:
class Dictionary { constructor () { this.items = {}; } set (key, value) { // 向字典中加在或修改元素 this.items[key] = value; } get (key) { // 通过键值查找字典中的值 return this.items[key]; } delete (key) { // 通过使用键值来从字典中删除对应的元素 if (this.has(key)) { delete this.items[key]; return true; } return false; } has (key) { // 判断给定的键值是否地处于字典中 return this.items.hasOwnProperty(key); } clear() { // 清空字典内容 this.items = {}; } size () { // 返回字典中所有元素的数量 return Object.keys(this.items).length; } keys () { // 返回字典中所有的键值 return Object.keys(this.items); } values () { // 返回字典中所有的值 return Object.values(this.items); } getItems () { // 返回字典中的所有元素 return this.items; } }
与Set类很例如,本来把其中value的偏离 替加在了key。亲戚亲戚我们来看看某些测试用例:
let Dictionary = require('./dictionary'); let dictionary = new Dictionary(); dictionary.set('Gandalf', 'gandalf@email.com'); dictionary.set('John', 'john@email.com'); dictionary.set('Tyrion', 'tyrion@email.com'); console.log(dictionary.has('Gandalf')); // true console.log(dictionary.size()); // 3 console.log(dictionary.keys()); // [ 'Gandalf', 'John', 'Tyrion' ] console.log(dictionary.values()); // [ 'gandalf@email.com', 'john@email.com', 'tyrion@email.com' ] console.log(dictionary.get('Tyrion')); // tyrion@email.com dictionary.delete('John'); console.log(dictionary.keys()); // [ 'Gandalf', 'Tyrion' ] console.log(dictionary.values()); // [ 'gandalf@email.com', 'tyrion@email.com' ] console.log(dictionary.getItems()); // { Gandalf: 'gandalf@email.com', Tyrion: 'tyrion@email.com' }
相应地,下面是使用ES6的原生Map类的测试结果:
let dictionary = new Map(); dictionary.set('Gandalf', 'gandalf@email.com'); dictionary.set('John', 'john@email.com'); dictionary.set('Tyrion', 'tyrion@email.com'); console.log(dictionary.has('Gandalf')); // true console.log(dictionary.size); // 3 console.log(dictionary.keys()); // [Map Iterator] { 'Gandalf', 'John', 'Tyrion' } console.log(dictionary.values()); // [Map Iterator] { 'gandalf@email.com', 'john@email.com', 'tyrion@email.com' } console.log(dictionary.get('Tyrion')); // tyrion@email.com dictionary.delete('John'); console.log(dictionary.keys()); // [Map Iterator] { 'Gandalf', 'Tyrion' } console.log(dictionary.values()); // [Map Iterator] { 'gandalf@email.com', 'tyrion@email.com' } console.log(dictionary.entries()); // [Map Iterator] { [ Gandalf: 'gandalf@email.com' ], [ Tyrion: 'tyrion@email.com' ] }
和前面亲戚亲戚我们自定义的Dictionary类稍微有某些不同,values()法律法律依据和keys()法律法律依据返回的完整版都不 有4个数组,本来Iterator迭代器。原来本来这里的size是有4个属性而完整版都不 法律法律依据,或者本来Map类没有 getItems()法律法律依据,取而代之的是entries()法律法律依据,它返回的也是有4个Iterator。有关Map类的完整版完整版介绍都只能查看这里。
在ES6中,除了原生的Set和Map类外,还有它们的弱化版本,分别是WeakSet和WeakMap,亲戚亲戚我们在《JavaScript数据底部形态——栈的实现与应用》一文中或者见过WeakMap的使用了。Map和Set与它们每该人的弱化版本之间的主要区别是:
- WeakSet或WeakMap类没有 entries、keys和values等迭代器法律法律依据,只能通过get和set法律法律依据访问和设置其中的值。这也是为哪些亲戚亲戚我们在《JavaScript数据底部形态——栈的实现与应用》一文中要使用WeakMap类来定义类的私有属性的原困。
- 只能用对应作为键值,或者说其中的内容只能是对象,而只能是数字、字符串、布尔值等基本数据类型。
弱化的Map和Set类主本来为了提供JavaScript代码的性能。
散列表
散列表(或者叫哈希表),是本身改进的dictionary,它将key通过有4个固定的算法(散列函数或哈希函数)得出有4个数字,或者将dictionary中key所对应的value存上放你你这个 数字所对应的数组下标所含晒 的存储空间中。在原始的dictionary中,或者要查找某个key所对应的value,亲戚亲戚我们只能遍历整个字典。为了提高查询的速度,亲戚亲戚我们将key对应的value保存到数组里,假如key不变,使用相同的散列函数计算出来的数字本来固定的,于是就都只能变慢地在数组中找到你让你查找的value。下面是散列表的数据底部形态示意图:
下面是亲戚亲戚我们散列函数loseloseHashCode()的实现代码:
loseloseHashCode (key) { let hash = 0; for (let i = 0; i < key.length; i++) { hash += key.charCodeAt(i); } return hash % 37; }
你你这个 散列函数的实现很简单,亲戚亲戚我们将传入的key中的每有4个字符使用charCodeAt()函数(有关该函数的完整版内容都只能查看这里)将其转加在ASCII码,或者将哪些ASCII码相加,最后用37求余,得到有4个数字,你你这个 数字本来你你这个 key所对应的hash值。接下来要做的本来将value存上放hash值所对应的数组的存储空间内。下面是亲戚亲戚我们的HashTable类的主要实现代码:
class HashTable { constructor () { this.table = []; } loseloseHashCode (key) { // 散列函数 let hash = 0; for (let i = 0; i < key.length; i++) { hash += key.charCodeAt(i); } return hash % 37; } put (key, value) { // 将键值对存上放哈希表中 let position = this.loseloseHashCode(key); console.log(`${position} - ${key}`); this.table[position] = value; } get (key) { // 通过key查找哈希表中的值 return this.table[this.loseloseHashCode(key)]; } remove (key) { // 通过key从哈希表中删除对应的值 this.table[this.loseloseHashCode(key)] = undefined; } isEmpty () { // 判断哈希表是否为空 return this.size() === 0; } size () { // 返回哈希表的长度 let count = 0; this.table.forEach(item => { if (item !== undefined) count++; }); return count; } clear () { // 清空哈希表 this.table = []; } }
测试一下上边的哪些法律法律依据:
let HashTable = require('./hashtable'); let hash = new HashTable(); hash.put('Gandalf', 'gandalf@email.com'); // 19 - Gandalf hash.put('John', 'john@email.com'); // 29 - John hash.put('Tyrion', 'tyrion@email.com'); // 16 - Tyrion console.log(hash.isEmpty()); // false console.log(hash.size()); // 3 console.log(hash.get('Gandalf')); // gandalf@email.com console.log(hash.get('Loiane')); // undefined hash.remove('Gandalf'); console.log(hash.get('Gandalf')); // undefined hash.clear(); console.log(hash.size()); // 0 console.log(hash.isEmpty()); // true
为了方便查看hash值和value的对应关系,亲戚亲戚我们在put()法律法律依据中加入了一行console.log(),用来打印key的hash值和value之间的对应关系。都只能想看 ,测试的结果和前面亲戚亲戚我们给出的示意图是一致的。
散列集合的实现和散列表例如,只不过在散列集合中不再使用键值对,本来只能值没有 键。你你这个 亲戚亲戚我们在前面介绍集合和字典的事先或者讲过了,这里不再赘述。
细心的同学或者或者发现了,这里亲戚亲戚我们提供的散列函数或者过于简单,以致于亲戚亲戚我们无法保证通过散列函数计算出来的hash值一定是唯一的。换句话说,传入不同的key值,亲戚亲戚我们有或者会得到相同的hash值。尝试一下下面哪些keys:
let hash = new HashTable(); hash.put('Gandalf', 'gandalf@email.com'); hash.put('John', 'john@email.com'); hash.put('Tyrion', 'tyrion@email.com'); hash.put('Aaron', 'aaron@email.com'); hash.put('Donnie', 'donnie@email.com'); hash.put('Ana', 'ana@email.com'); hash.put('Jamie', 'jamie@email.com'); hash.put('Sue', 'sue@email.com'); hash.put('Mindy', 'mindy@email.com'); hash.put('Paul', 'paul@email.com'); hash.put('Nathan', 'nathan@email.com');
从结果中都只能想看 ,尽管某些keys不同,或者通过亲戚亲戚我们提供的散列函数岂完整版都不 得到了相同的hash值,这显然违背了亲戚亲戚我们的设计原则。在哈希表中,你你这个 叫做散列冲突,为了得到有4个可靠的哈希表,亲戚亲戚我们只能尽或者地正确处理散列冲突。那如何正确处理你你这个 冲突呢?这里介绍本身正确处理冲突的法律法律依据:分离链接和线性探查。
分离链接
所谓分离链接,本来将原来存储在哈希表中的值改成链表,原来在哈希表的同有4个位置上,就都只能存储多个不同的值。链表中的每有4个元素,一起去存储了key和value。示意图如下:
原来,当不同的key通过散列函数计算出相同的hash值时,亲戚亲戚我们只只能找到数组中对应的位置,或者往其中的链表加在新的节点即可,从而有效地正确处理了散列冲突。为了实现你你这个 数据底部形态,亲戚亲戚我们只能定义有4个新的辅助类ValuePair,它的内容如下:
let ValuePair = function (key, value) { this.key = key; this.value = value; this.toString = function () { // 提供toString()法律法律依据以方便亲戚亲戚我们测试 return `[${this.key} - ${this.value}]`; } };
ValuePair类具有4个属性,key和value,用来保存亲戚亲戚我们要存入到散列表中的元素的键值对。toString()法律法律依据在这里完整版都不 只能的,该法律法律依据是为了上边亲戚亲戚我们方便测试。
新的采用了分离链接的HashTableSeparateChaining类都只能继承自前面的HashTable类,完整版的代码如下:
class HashTableSeparateChaining extends HashTable { constructor () { super(); } put (key, value) { let position = this.loseloseHashCode(key); if (this.table[position] === undefined) { this.table[position] = new LinkedList(); // 单向链表,只能引入LinkedList类 } this.table[position].append(new ValuePair(key, value)); } get (key) { let position = this.loseloseHashCode(key); if (this.table[position] !== undefined) { let current = this.table[position].getHead(); while (current) { if (current.element.key === key) return current.element.value; current = current.next; } } return undefined; } remove (key) { let position = this.loseloseHashCode(key); let hash = this.table[position]; if (hash !== undefined) { let current = hash.getHead(); while (current) { if (current.element.key === key) { hash.remove(current.element); if (hash.isEmpty()) this.table[position] = undefined; return true; } current = current.next; } } return false; } size () { let count = 0; this.table.forEach(item => { if (item !== undefined) count += item.size(); }); return count; } toString() { let objString = ""; for (let i = 0; i < this.table.length; i++) { let ci = this.table[i]; if (ci === undefined) continue; objString += `${i}: `; let current = ci.getHead(); while (current) { objString += current.element.toString(); current = current.next; if (current) objString += ', '; } objString += '\r\n'; } return objString; } }
其中的LinkedList类为单向链表,具体内容都只能查看《JavaScript数据底部形态——链表的实现与应用》。注意,现在hash数组中的每有4个元素完整版都不 有4个单向链表,单向链表的所有操作亲戚亲戚我们都只能借促使LinkedList类来完成。亲戚亲戚我们重写了size()法律法律依据,或者现在要计算的是数组中所有链表的长度总和。
下面是HashTableSeparateChaining类的测试用例及结果:
let hash = new HashTableSeparateChaining(); hash.put('Gandalf', 'gandalf@email.com'); hash.put('John', 'john@email.com'); hash.put('Tyrion', 'tyrion@email.com'); hash.put('Aaron', 'aaron@email.com'); hash.put('Donnie', 'donnie@email.com'); hash.put('Ana', 'ana@email.com'); hash.put('Jamie', 'jamie@email.com'); hash.put('Sue', 'sue@email.com'); hash.put('Mindy', 'mindy@email.com'); hash.put('Paul', 'paul@email.com'); hash.put('Nathan', 'nathan@email.com'); console.log(hash.toString()); console.log(`size: ${hash.size()}`); console.log(hash.get('John')); console.log(hash.remove('Ana')); console.log(hash.remove('John')); console.log(hash.toString());
都只能想看 ,结果和上边示意图上给出的是一致的,size()、remove()和get()法律法律依据的执行结果也符合预期。
线性探查
正确处理散列冲突的另本身法律法律依据是线性探查。当向哈希数组中加在某有4个新元素时,或者该位置上或者有数据了,就继续尝试下有4个位置,直到对应的位置上没有 数据时,就在该位置加在在数据。亲戚亲戚我们将上边的例子改成线性探查的法律法律依据,存储结果如下图所示:
现在亲戚亲戚我们不只能单向链表LinkedList类了,或者ValuePair类仍然是只能的。同样的,亲戚亲戚我们的HashTableLinearProbing类继承自HashTable类,完整版的代码如下:
class HashTableLinearProbing extends HashTable { constructor () { super(); } put (key, value) { let position = this.loseloseHashCode(key); if (this.table[position] === undefined) { this.table[position] = new ValuePair(key, value); } else { let index = position + 1; while (this.table[index] !== undefined) { index ++; } this.table[index] = new ValuePair(key, value); } } get (key) { let position = this.loseloseHashCode(key); if (this.table[position] !== undefined) { if (this.table[position].key === key) return this.table[position].value; let index = position + 1; while (this.table[index] !== undefined && this.table[index].key === key) { index ++; } return this.table[index].value; } return undefined; } remove (key) { let position = this.loseloseHashCode(key); if (this.table[position] !== undefined) { if (this.table[position].key === key) { this.table[position] = undefined; return true; } let index = position + 1; while (this.table[index] !== undefined && this.table[index].key !== key) { index ++; } this.table[index] = undefined; return true; } return false; } toString() { let objString = ""; for (let i = 0; i < this.table.length; i++) { let ci = this.table[i]; if (ci === undefined) continue; objString += `${i}: ${ci}\r\n`; } return objString; } }
使用上边和HashTableSeparateChaining类相同的测试用例,亲戚亲戚我们来看看测试结果:
都只能和HashTableSeparateChaining类的测试结果比较一下,多出来的位置6、14、17、33,正是HashTableSeparateChaining类中每有4个链表的剩余偏离 。get()和remove()法律法律依据都可不里能正常工作,亲戚亲戚我们不只能重写size()法律法律依据,和基类HashTable中一样,hash数组中每有4个位置只保存了有4个元素。原来要注意的地方是,或者JavaScript中定义数组时不只能提前给出数组的长度,或者亲戚亲戚我们都只能很容易地利用JavaScript语言的你你这个 底部形态来实现线性探查。在某些编程语言中,数组的定义是只能明确给出长度的,这时亲戚亲戚我们就只能重新考虑亲戚亲戚我们的HashLinearProbing类的实现了。
loseloseHashCode()散列函数并完整版都不 有4个表现良好的散列函数,正如你所想看 的,它会很轻易地产生散列冲突。有4个表现良好的散列函数只里都可不里能尽或者低地减少散列冲突,并提高性能。亲戚亲戚我们都只能在网上找某些不同的散列函数的实现法律法律依据,下面是有4个比loseloseHashCode()更好的散列函数djb2HashCode():
djb2HashCode (key) { let hash = 5381; for (let i = 0; i < key.length; i++) { hash = hash * 33 + key.charCodeAt(i); } return hash % 1013; }
亲戚亲戚我们用相同的测试用例来测试dj2HashCode(),下面是测试结果:
这次没有 冲突!然而这并完整版都不 最好的散列函数,但它是社区最推崇的散列函数之一。
下一章亲戚亲戚我们将介绍如何用JavaScript来实现树。