重学数据结构与算法(四)
·哈希表
-
hash:把任意长度的输入通过hash函数变为固定长度的输出,这个输出就是hash值(散列值)例如:MD5
-
hash表(散列表):是根据关键码可以直接访问的数据结构,关键码通过哈希函数得到固定长度的散列值,将散列值作为索引来利用数组存储对应的数据,这种数组就是哈希表。
/* 哈希表 */ class hashTable { constructor () { this.items = [] } // 存储数据 set (val, key) { let i = this.hash(key) this.items[i] = val } // 获取数据 get (key) { let i = this.hash(key) return this.items[i] } // 一个最最最最简单的hash函数 hash (key) { return key.charCodeAt() % 37 } } const ht = new hashTable() ht.set(1234, 'zsjfjg') ht.set(345, 'A') ht.set(0000, 'asdfg') console.log(ht.items) console.log(ht.get('A')) // 345
-
冲突处理:一个好的哈希算法会尽可能就减小冲突的可能,但是实际情况中冲突是不可避免的,如果解决不了冲突问题,用哈希表来存储数据是没有意义的,因为产生冲突后会覆盖原来的数据,造成数据丢失。
- 开发寻址法
- 链地址法:在数组的value处存储一个指向链表的地址,所有元素依次存入链表
- 再散列法:再次用哈希算法得到一个关键码
·二叉搜索树
- 二叉搜索树:又称二叉排序树、二叉查找树。一种特殊的二叉树,如果左子树不空,则左子树上的所有节点都小于根结点,如果右子树不空,则右子树上的结点都大于根结点,且左右子树也都是二叉搜索树。
- 遍历:先序遍历、中序遍历、后序遍历。序:指根结点被访问的顺序
- 查找:查找结点
/*
二叉搜索树
*/
// 结点类
class Node {
constructor (val) {
this.value = val
this.left = null
this.right = null
}
}
// 二叉搜索类
class BinarySearchTree {
constructor () {
this.root = null
}
// 结点比较大小
relaNode (node, newnode) {
if (node.value > newnode) {
if (node.left === null) {
node.left === newnode
} else {
this.relaNode(node.left, newnode)
}
}
if (node.value < newnode) {
if (node.right === null) {
node.right === newnode
} else {
this.relaNode(node.right, newnode)
}
}
}
// 存储
set (val) {
const newnode = new Node(val)
if (this.root === null) {
this.root = newnode
} else {
this.relaNode(this.root, newnode)
}
}
// DLR 先序遍历
dlr (node, cb) {
if (node.value === null) {
return
}
cb(node.value)
this.dlr(node.left, cb)
this.dlr(node.right, cb)
}
// LDR 中序遍历
dlr (node, cb) {
if (node.value === null) {
return
}
this.dlr(node.left, cb)
cb(node.value)
this.dlr(node.right, cb)
}
// LRD 后序遍历
dlr (node, cb) {
if (node.value === null) {
return
}
this.dlr(node.left, cb)
this.dlr(node.right, cb)
cb(node.value)
}
// 回调函数
cb (val) {
const arr = []
arr.push(val)
}
// 查询
search (val) {
const node = this.root
while (node.value !== val) {
if (node.value > val) {
node = node.left
} else if (node.value < val) {
node = node.right
} else {
return true
}
}
}
}