• lintcode-128-哈希函数


    128-哈希函数

    在数据结构中,哈希函数是用来将一个字符串(或任何其他类型)转化为小于哈希表大小且大于等于零的整数。一个好的哈希函数可以尽可能少地产生冲突。一种广泛使用的哈希函数算法是使用数值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和一个哈希表的大小,返回这个字符串的哈希值。

    说明

    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.

    样例

    对于key="abcd" 并且 size=100, 返回 78

    标签

    哈希表

    思路

    不需自己实现hash算法,按题目内容来就行

    code

    class Solution {
    public:
        /**
         * @param key: A String you should hash
         * @param HASH_SIZE: An integer
         * @return an integer
         */
        int hashCode(string key,int HASH_SIZE) {
            // write your code here
            int size = key.size();
            if(size <= 0) {
                return 0;
            }
            long code = 0; 
            long hashBase = 1;
            for(int i=size-1; i>=0; i--) {
                code = code + (key[i] * hashBase) % HASH_SIZE;
                code %= HASH_SIZE;
                hashBase = hashBase * 33 % HASH_SIZE;
            }
            return code;
        }
    };
    
  • 相关阅读:
    集合框架之Map学习
    集合框架之Set学习
    解决word2016鼠标每点击一下就出现一个保存的圆圈
    装饰者模式
    IO的学习与使用
    Enumeration的学习
    在html页面中引入公共的头部和底部
    WEB-INF下资源访问问题
    给自己立一个flag
    elementui 日期选择值格式
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7217165.html
Copyright © 2020-2023  润新知