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()办法返回的都是一一个多 数组,要是Iterator迭代器。另一一个多 要是这里的size是一一个多 属性而都是办法,为什么会么会让要是Map类没法 getItems()办法,取而代之的是entries()办法,它返回的也是一一个多 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通过一一个多 固定的算法(散列函数或哈希函数)得出一一个多 数字,为什么会么会让将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中的每一一个多 字符使用charCodeAt()函数(有关该函数的完正内容都前要查看这里)将其转上加ASCII码,为什么会么会让将什么ASCII码相加,最后用37求余,得到一一个多 数字,本身生活数字要是本身生活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值,这显然违背了亲戚亲戚你们你们的设计原则。在哈希表中,本身生活叫做散列冲突,为了得到一一个多 可靠的哈希表,亲戚亲戚你们你们前要尽机会地避免散列冲突。那怎么都可以避免本身生活冲突呢?这里介绍本身生活避免冲突的办法:分离链接和线性探查。
分离链接
所谓分离链接,要是将另一一个多 存储在哈希表中的值改成链表,另一一个多 在哈希表的同一一个多 位置上,就都前要存储多个不同的值。链表中的每一一个多 元素,一同存储了key和value。示意图如下:
另一一个多 ,当不同的key通过散列函数计算出相同的hash值时,亲戚亲戚你们你们只前要找到数组中对应的位置,为什么会么会让往其中的链表上加新的节点即可,从而有效地避免了散列冲突。为了实现本身生活数据型态,亲戚亲戚你们你们前要定义一一个多 新的辅助类ValuePair,它的内容如下:
let ValuePair = function (key, value) { this.key = key; this.value = value; this.toString = function () { // 提供toString()办法以方便亲戚亲戚你们你们测试 return `[${this.key} - ${this.value}]`; } };
ValuePair类具有一一个多 属性,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数组中的每一一个多 元素都是一一个多 单向链表,单向链表的所有操作亲戚亲戚你们你们都前要借有利于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()办法的执行结果也符合预期。
线性探查
避免散列冲突的另本身生活办法是线性探查。当向哈希数组中上加某一一个多 新元素时,机会该位置上机会有数据了,就继续尝试下一一个多 位置,直到对应的位置上没法 数据时,就在该位置上上加数据。亲戚亲戚你们你们将里面的例子改成线性探查的办法,存储结果如下图所示:
现在亲戚亲戚你们你们不前要单向链表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类中每一一个多 链表的剩余每项。get()和remove()办法并能正常工作,亲戚亲戚你们你们不前要重写size()办法,和基类HashTable中一样,hash数组中每一一个多 位置只保存了一一个多 元素。另一一个多 要注意的地方是,机会JavaScript中定义数组时不前要提前给出数组的长度,为什么会么会让亲戚亲戚你们你们都前要很容易地利用JavaScript语言的本身生活型态来实现线性探查。在或多或少编程语言中,数组的定义是前要明确给出长度的,这时亲戚亲戚你们你们就前要重新考虑亲戚亲戚你们你们的HashLinearProbing类的实现了。
loseloseHashCode()散列函数从都是一一个多 表现良好的散列函数,正如你所看得人的,它会很轻易地产生散列冲突。一一个多 表现良好的散列函数前要并能尽机会低地减少散列冲突,并提高性能。亲戚亲戚你们你们都前要在网上找或多或少不同的散列函数的实现办法,下面是一一个多 比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来实现树。