递归-----Hash Function

本文详细介绍了哈希函数的原理与应用,包括如何将字符串转换为整数,避免碰撞,以及具体实现方法。通过实例展示了哈希值的计算过程,并提供了相应的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.f

Have you met this question in a real interview? Yes
Example
For key=”abcd” and size=100, return 78

Clarification
For this problem, you are not necessary to design your own hash algorithm or consider any collision issue, you just need to implement the algorithm as described.

要点(a + b) % p = (a % p + b % p) % p

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) {
        if (key.length == 0) return 0;
        int result = 0;
        int base = 1;
        for (int i=key.length-1; i>=0; i--) {
            int num = (int)(key[i] - '\0');
            result += modMultiply(num, base, HASH_SIZE);
            result = result % HASH_SIZE;
            base = modMultiply(base, 33, HASH_SIZE);
        }
        return result % HASH_SIZE;
    }

    public int modMultiply(int a, int b, int c) {
        long temp = (long)a * b;
        return (int)(temp % c);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值