LintCode 128. Hash function JavaScript algorithm

description

In the data structure, the hash function is used to convert a string (or any other type) into an integer less than the size of the hash table and greater than or equal to zero. A good hash function can produce as few collisions as possible. A widely used hash function algorithm is to use the value 33, assuming that any string is based on a large integer of 33, such as:

hashcode(“abcd”) = (ascii(a) * 33^3 + ascii(b) * 33^2 + ascii© 33 + ascii(d)) % HASH_SIZE
= (97
33^3 + 98 * 33^2 + 99 * 33 +100) % HASH_SIZE
= 3595978 % HASH_SIZE

HASH_SIZE represents the size of the hash table (it can be assumed that a hash table is an array with an index of 0 ~ HASH_SIZE-1).

Given a string as the key and the size of a hash table, return the hash value of this string.

Description

For this problem, you do not need to design your own hash algorithm or consider any conflict issues, you only need to implement the algorithm as described.

Sample

- 样例 1:

输入:  key = "abcd", size = 1000
输出: 978	
样例解释:(97 * 33^3 + 98*33^2 + 99*33 + 100*1)%1000 = 978

- 样例 2:

输入:  key = "abcd", size = 100
输出: 78	
样例解释:(97 * 33^3 + 98*33^2 + 99*33 + 100*1)%100 = 78

Parsing

hashCode = (key, HASH_SIZE) => {
    
    
    result=0;
    for(i=0;i<key.length;i++){
    
    
        result=(key[i].charCodeAt()+result*33)%HASH_SIZE
    }
    return result;
};

operation result

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/SmallTeddy/article/details/108724545