LintCode_128 Hash Function
来源:互联网 发布:手机投影画画软件 编辑:程序博客网 时间:2024/06/06 16:42
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.f
要注意的问题是计算过程中可能数值过大超出int的范围, 所以要用long来实现,被操作数一定要用long来实现,否则两个int类型进行计算,可能先溢出了,再赋值给long,结果还是溢出的结果,long并没有起作用。
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.size() == 0) return 0; int len = (int)key.size(); long factor = 1; long res = 0; for (int i = len - 1 ; i >= 0; i--) { if (i == len - 1) { res+=key[i] % HASH_SIZE; continue; } factor = (factor * 33) % HASH_SIZE; res+=(key[i] * factor) % HASH_SIZE; //cout<<key[i]<<" "<<(key[i] * factor) % HASH_SIZE<<endl; //cout<<res<<endl; } return res % HASH_SIZE; }};
- LintCode_128 Hash Function
- Hash Function
- Hash Function
- RS Hash Function
- hash function for proxy
- zoj3618 Hash Function
- [刷题]Hash Function
- 递归-----Hash Function
- #128 Hash Function
- A Hash Function for Hash Table Lookup
- 关于hash function的文章
- DJB hash function for strings
- hash function比较(一)
- General Purpose Hash Function Algorithms
- Hash Quadratic function (二次探测)
- Robert Jenkin's hash function
- Hash Function 哈希函数
- Lintcode128 Hash Function solution 题解
- 一道常被人轻视的前端JS面试题
- 继承一个类的时候报错:The hierarchy of the type 'Class name' is inconsistent
- 使用log.i和Toast.makeText进行Android开发测试
- IOS 同步异步请求JSON数据
- fill_parent、wrap_content和match_parent的区别
- LintCode_128 Hash Function
- sql server 安装错误
- Java 异常处理
- 用黑暗森林模型理解TCP的三次握手
- Java字节序,java整型数与网络字节序 byte[] 数组转换关系
- 关于JavaScript的变量与函数申明的置前
- 设计模式-桥接模式
- JavaEE学习笔记之Servlet/JSP(2)
- Quartz