java - 为可能为负的整数实现双重哈希

标签 java c++ hash double-hashing

我正在使用双重哈希方法为整数实现一个哈希类。输入将是随机整数,可以是正数也可以是负数。

我的问题是如何计算负整数的哈希值?

这是方法:

hash function 1 h: h(k) = k mod (p)
hash function 2 s(k)= p –2 – (k mod(p-2))
p = table size, k = key

计算完h(k)后,如果没有碰撞,就插到它的位置上。如果发生冲突,我将计算 (h(k) + s(k)) mod p 并将 key 存储在计算结果值中。

所以我的问题是如果 key 是一个负整数,我应该在散列之前取它的绝对值(使其为正值)吗?或者还有其他方法吗?

最佳答案

来自Princeton Algorithms website :

Q: What's wrong with using (s.hashCode() % M) or Math.abs(s.hashCode()) % M to hash to a value between 0 and M-1?

A: The % operator returns a non-positive integer if its first argument is negative, and this would create an array index out-of-bounds error. Surprisingly, the absolute value function can even return a negative integer. This happens if its argument is Integer.MIN_VALUE because the resulting positive integer cannot be represented using a 32-bit two's complement integer. This kind of bug would be excruciatingly difficult to track down because it would only occur one time in 4 billion! [ The String hash code of "polygenelubricants" is -2^31. ]

Java 从哈希码 as follows 计算索引:

 static int indexFor(int hashcode, int length) {
     return hashcode & (length-1);
 }

关于java - 为可能为负的整数实现双重哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30018125/

相关文章:

c++ - 是否可以将 Arial Unicode 等 unicode 字体拆分为特定语言 block (例如泰语)?

javascript - 使用 jQuery 在特定点加载页面(没有动画!)

perl - 不能使用字符串 ("0") 作为哈希引用

c++ - Karp Rabin 中的质数和 block 长度

Java if else 部分匹配

java - 为什么动态编程和朴素解决方案需要相同的执行时间?

java - Maven 可执行 jar 打包 vs Maven exec with Jackson 不工作

用于计算矩阵指数的 C++ 库

c++ - 互斥锁出错了?

java - libgdx 中 BoundingBox 和 Sphere 之间的碰撞检测