【題目描述】
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.
在數據結構中,哈希函數是用來將一個字符串(或任何其他類型)轉化爲小於哈希表大小且大於等於零的整數。一個好的哈希函數可以儘可能少地產生衝突。一種廣泛使用的哈希函數算法是使用數值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和一個哈希表的大小,返回這個字符串的哈希值
【題目鏈接】
[www.lintcode.com/en/problem/hash-function/]()
【題目解析】
基本實現題,大多數人看到題目的直覺是按照定義來遞推,但其實這裏面大有玄機,因爲在字符串較長時使用long 型來計算33的冪會溢出!所以這道題的關鍵在於如何處理大整數溢出。對於整數求模,(a b) % m = a % m b % m這個基本公式務必牢記。根據這個公式我們可以大大降低時間複雜度和規避溢出。
【參考答案】
[www.jiuzhang.com/solutions/hash-function/]()