博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Lintcode128 Hash Function solution 题解
阅读量:7244 次
发布时间:2019-06-29

本文共 1468 字,大约阅读时间需要 4 分钟。

【题目描述】

In data structure Hash, hash function is used to convert a string(or any other type) into an integer smaller than hash size and bigger or equal to zero. The objective of designing a hash function is to "hash" the key as unreasonable as possible. A good hash function can avoid collision as less as possible. A widely used hash function algorithm is using a magic number 33, consider any string as a 33 based big integer like follow:

hashcode("abcd") = (ascii(a) 333+ ascii(b) 332+ ascii(c) *33 + ascii(d)) % HASH_SIZE

= (97 333+ 98  332+ 99 * 33 +100) % HASH_SIZE

= 3595978 % HASH_SIZE

here HASH_SIZE is the capacity of the hash table (you can assume a hash table is like an array with index 0 ~ HASH_SIZE-1).

Given a string as a key and the size of hash table, return the hash value of this key.

在数据结构中,哈希函数是用来将一个字符串(或任何其他类型)转化为小于哈希表大小且大于等于零的整数。一个好的哈希函数可以尽可能少地产生冲突。一种广泛使用的哈希函数算法是使用数值33,假设任何字符串都是基于33的一个大整数,比如:

hashcode("abcd") = (ascii(a) 333+ ascii(b) 332+ ascii(c) *33 + ascii(d)) % HASH_SIZE

= (97 333+ 98  332+ 99 * 33 +100) % HASH_SIZE

= 3595978 % HASH_SIZE

其中HASH_SIZE表示哈希表的大小(可以假设一个哈希表就是一个索引0 ~ HASH_SIZE-1的数组)。

给出一个字符串作为key和一个哈希表的大小,返回这个字符串的哈希值

【题目链接】

[www.lintcode.com/en/problem/hash-function/]()

【题目解析】

基本实现题,大多数人看到题目的直觉是按照定义来递推,但其实这里面大有玄机,因为在字符串较长时使用long 型来计算33的幂会溢出!所以这道题的关键在于如何处理大整数溢出。对于整数求模,(a b) % m = a % m b % m这个基本公式务必牢记。根据这个公式我们可以大大降低时间复杂度和规避溢出。

【参考答案】

[www.jiuzhang.com/solutions/hash-function/]()

转载于:https://blog.51cto.com/13517018/2051413

你可能感兴趣的文章
求旋转后的数组Bk中下标与对应数值的乘积的最大值 Rotate Function
查看>>
《大数据的冲击》迷你书
查看>>
经常用Linux 但是你知道它和Unix区别吗?
查看>>
Android编译报R.java报不到的错误解决办法
查看>>
CentOS5.x下安装配置FTP服务器
查看>>
正则数量词及非捕获
查看>>
MPLS 配置步骤
查看>>
Exchange Server 2007灾难恢复(AD+Ex)
查看>>
GRUB2
查看>>
用Java数字签名提供XML安全
查看>>
我的友情链接
查看>>
从usb监控做起防公司泄密
查看>>
A case for Tmux tool
查看>>
linux利用screen命令管理远程会话
查看>>
switch-case语句问题
查看>>
Go性能优化技巧 1/10
查看>>
DNS 域名解析服务器---案例详解
查看>>
疑似电信版GALAXY S4现身官网 或配八核处理器
查看>>
我的Linux生涯之系统语言环境及中文输入法的操作
查看>>
c#获取当前页面名字
查看>>