博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
lintcode-easy-Hash Function
阅读量:4503 次
发布时间:2019-06-08

本文共 1770 字,大约阅读时间需要 5 分钟。

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.

 

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.

 

这道题要注意的就是溢出,要注意两点:

1. 使用long类型

2. 每次计算33的n次方要再做%HASH_SIZE,每一项累加之后也要%HASH_SIZE避免溢出

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        if(key == null || key.length == 0)              return 0;                long factor = 1;        long result = 0;                for(int i = key.length - 1; i >= 0; i--){            result += (((int) key[i]) * factor) % HASH_SIZE;            factor = (factor * 33) % HASH_SIZE;                    }                result %= HASH_SIZE;                return (int) result;    }};

 

转载于:https://www.cnblogs.com/goblinengineer/p/5215685.html

你可能感兴趣的文章
jquery next()方法
查看>>
深入剖析js命名空间函数namespace
查看>>
SQLHelper
查看>>
用标准Struts2+mvc写的用户管理
查看>>
Cocos2d-x 3.0 编译出错 解决 error: expected ';' at end of member declaration
查看>>
Ubuntu12.04下载Repo
查看>>
python基础教程_学习笔记10:异常
查看>>
MATLAB——scatter的简单应用
查看>>
linux下复制粘贴快捷键
查看>>
什么是对象
查看>>
记录开发小程序
查看>>
WinSock服务程序
查看>>
巴西柔术第五课:过腿
查看>>
文件的操作
查看>>
网上图书商城项目学习笔记-007登录功能实现
查看>>
关于mysql的级联删除(之前好多人咨询过我)
查看>>
Linux环境下的C/C+基础调试技术2——程序控制
查看>>
wpf动画同步闪烁
查看>>
3.16上午 复习雅思核心词+新单词100个
查看>>
Html5 部分特性
查看>>