当前位置: 代码网 > it编程>编程语言>Javascript > 数据结构Typescript之哈希表实现详解

数据结构Typescript之哈希表实现详解

2024年05月18日 Javascript 我要评论
哈希表的结构特点相比链表繁杂的遍历处理,哈希表的作用是存储无固定顺序的键值对。哈希表的元素查找时间复杂度为o(1)。尝试手动构建一个哈希表。过程如下:function hashcode(str) {

哈希表的结构特点

相比链表繁杂的遍历处理,哈希表的作用是存储无固定顺序的键值对哈希表的元素查找时间复杂度为o(1)

尝试手动构建一个哈希表。过程如下:

function hashcode(str) { // 散列函数
    let address = 0
    for (let i = 0; i < str.length; i++) {
        address += str.charcodeat(i)
    }
    return address % 37 // 生成的哈希码
}
let table = {} // 哈希表
let keyvaluepair = { key: "苹果手机", value: "4999元" } // 哈希表的基本单元: 键值对
table[hashcode(keyvaluepair.key)] = keyvaluepair // table添加对象,属性为哈希码,值为keyvaluepair
console.log(table) // 输出哈希表: table { 28: { key: "苹果手机", value: "4999元" } }

我们需要清楚哈希表、键值对、哈希码和散列函数这四者的关系。过程分析如下:

第一步:创建哈希表table、键值对keyvaluepair和散列函数hashcode

第二步:基于keyvaluepair.key即"苹果手机"这个字符串特征,通过散列函数生成哈希码hashcode(keyvaluepair.key)

第三步:执行table[hashcode(keyvaluepair.key)] = keyvaluepair。即在table对象上新增一个hashcode(keyvaluepair.key)属性,而它的值就是键值对keyvaluepair

总结:键值对中的key可通过散列函数生成哈希码,而生成的哈希码则作为哈希表的属性存储对应的键值对。

面向对象方法封装哈希表

哈希冲突

试着考虑以下这种情况,我们需要存储的键由相同字母构成,但字母的排序不同。

console.log(hashcode('mike')) // 20
console.log(hashcode('meki')) // 20
console.log(hashcode('kemi')) // 20

显然,相同字符构成但排序不同的字符串会生成相同的哈希码。即在哈希表中我们原来存储的键值对可能会因为哈希冲突而产生被覆盖的情况。有很多手段可以解决哈希冲突的问题。本文采取的是链地址方法。

构造函数

基本单元:键值对

class keyvaluepair {
    key: any
    value: any
    constructor(key: any, value: any) {
        this.key = key
        this.value = value
    }
}

主体:哈希表

class hashtable {
    length: number
    table: { [index: number]: linkedlist }
    constructor() {
        this.length = 0
        this.table = {}
    }
}

增加键值对

增加键值对的情况分为两种。如下分析:

  • 哈希表中没有这个哈希码属性:创建一个新链表,然后将键值对作为头节点插入链表。
  • 哈希表中已存在相同的哈希码:即存在哈希冲突,在已创建的链表上追加一个键值对。
set(key: any, value: any): hashtable {
    if (this.table[hashcode(key)] === undefined) {
        this.table[hashcode(key)] = new linkedlist()
    }
    this.table[hashcode(key)].insert(new keyvaluepair(key, value))
    this.length++
    return this
}

获取键值

获取键值的情况分为三种。如下分析:

  • 哈希表为空:抛出错误。
  • 哈希表中不存在这个哈希码属性:抛出错误。
  • 哈希表中存在这个哈希码属性:从头节点开始,遍历链表找到这个key参数对应的键值返回,否则抛出错误。
get(key: any): (void | any) {
    if (this.isempty()) {
        throw new error(`hashtable is empty`)
    } else if (this.table[hashcode(key)] === undefined) {
        throw new error(`${key} is not defined`)
    } else {
        let current: (null | linkedlistnode) = this.table[hashcode(key)].head
        while (current !== null) {
            if (key === current!.element!.key) {
                return current!.element!.value
            }
            current = current!.next
        }
        if (!current) { throw new error(`${key} does not exist`) }
    }
}

删除键值对

删除键值对的情况分为三种。如下分析:

  • 哈希表为空:抛出错误。
  • 哈希表中不存在这个哈希码属性:抛出错误。
  • 哈希表中存在这个哈希码属性:链表长度为1,直接删除这个哈希码属性。链表长度大于1,遍历链表获取这个键值对在链表中对应的序号,然后利用链表方法删除这个键值对。
remove(key: any): hashtable {
    if (this.isempty()) {
        throw new error(`hashtable is empty`)
    } else if (this.table[hashcode(key)] === undefined) {
        throw new error(`${key} is not defined`)
    } else if (this.table[hashcode(key)].length === 1) {
        delete this.table[hashcode(key)]
    } else if (this.table[hashcode(key)].length &gt; 1) {
        let current: (null | linkedlistnode) = this.table[hashcode(key)].head
        for (let i = 0; i &lt; this.table[hashcode(key)].length; i++) {
            if (key === current!.element!.key) {
                this.table[hashcode(key)].remove(i)
                break
            }
            current = current!.next
        }
        if (!current) { throw new error(`${key} does not exist`) }
    }
    this.length--
    return this
}

本文相关代码已放置我的github仓库 👇

项目地址:algorithmlib|hashtable

以上就是数据结构typescript之哈希表实现详解的详细内容,更多关于typescript数据结构哈希表的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com