題目地址:
https://www.lintcode.com/problem/hash-function/description
給定一個字符串,給定一個數定義其哈希函數爲。要求計算其哈希值。
要用long來做,以防溢出,最後轉成int。代碼如下:
public 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
long res = 0;
if (key == null || key.length == 0) {
return 0;
}
for (int i = 0; i < key.length; i++) {
res = res * 33 + key[i];
res %= HASH_SIZE;
}
return (int) res;
}
}
時間複雜度,空間。