哈希函数-LintCode
来源:互联网 发布:人工智能专家系统 编辑:程序博客网 时间:2024/06/18 04:28
在数据结构中,哈希函数是用来将一个字符串(或任何其他类型)转化为小于哈希表大小且大于等于零的整数。一个好的哈希函数可以尽可能少地产生冲突。一种广泛使用的哈希函数算法是使用数值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和一个哈希表的大小,返回这个字符串的哈希值。
说明
For this problem, you are not necessary to design your own hash algorithm or consider any collision issue, you just need to implement the algorithm as described.
样例
对于key=”abcd” 并且 size=100, 返回 78
class Solution {public: /** * @param key: A String you should hash * @param HASH_SIZE: An integer * @return an integer */ int hashCode(string key,int HASH_SIZE) { // write your code here if (key.empty()) return 0; int len = key.size(); long int accout = (int)key[0]; for (int i = 1; i < len; ++i) { accout =accout*33%HASH_SIZE+(int)key[i]; } return accout%HASH_SIZE; }};
阅读全文
0 0
- 哈希函数-LintCode
- lintcode:哈希函数
- LintCode HashFunction 哈希函数
- LintCode之哈希函数
- LintCode——哈希函数
- lintcode-哈稀函数-128
- lintCode(128)——哈希函数
- LintCode
- lintcode--
- lintcode
- LintCode
- Lintcode
- LintCode(M)带min函数的栈
- LintCode Consistent Hashing(一致性哈希算法)
- LintCode Consistent Hashing II(一致性哈希算法II)
- Lintcode - Median
- Lintcode - MedianII
- Lintcode - Heapify
- 消息队列通信方式为什么在内核和用户空间进行四次的数据拷贝
- 用Swing开发GUI程序(一)
- 跳跃游戏二
- C++读入输出的优化模板
- 对象的多态性
- 哈希函数-LintCode
- Eclipse常用快捷键大全。
- 阿里镜像Maven
- FileUtils
- Elasticsearch5.0安装
- javascripta中运算符的优先级
- 常用的网络故障排错方法
- 分布式和集群例子理解
- python多进程中的进程池pool