CS182 离散数学学到的知识派上用场了,系统学习知识很有必要,对于一个概念的理解会更深刻。不过,182的问题在于太理论,不注重实践。我第一时间没有想到需要先求余,说明理论到实践这一步还需要加强。
象牙塔和社会之间的差别往往是如此,考试的题目和课堂的知识点是对应的。试卷上的问题,我们很自然的知道应该用第几章的哪个定理去解决,可是现实的问题往往复杂得多,没有人告诉你需要如何解决。
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) * 33^3 + ascii(b) * 33^2 + ascii(c) 33 + ascii(d)) % HASH_SIZE
= (97 33^3 + 98 * 33^2 + 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.
class Solution {
/**
* @param key: A String you should hash
* @param HASH_SIZE: An integer
* @return an integer
*/
public int hashCode(char[] key,int HASH_SIZE) {
// write your code here
if (key == null) return 0;
int n = key.length;
long sum = 0;
for (int i = 0; i < n; i++) {
sum = (sum * 33 + key[i]) % HASH_SIZE;
}
return (int)sum;
}
};