这道题没有什么算法难点,公式已经给出了,重点是一些函数的使用和时间复杂度的问题。python
字符串转换函数:算法
注意这里不能用int()
函数进行转化,由于该函数的输入值只是时数字。函数
class Solution:
""" @param key: A string you should hash @param HASH_SIZE: An integer @return: An integer """
def hashCode(self, key, HASH_SIZE):
# write your code here
n = len(key)
num = 0
for i in range(n):
num += ord(key[i])*(33**(n-i-1))
num = num % HASH_SIZE
return num
复制代码
可是上边这个程序会报超时的错误,接下来考虑怎么下降时间复杂度。由于自己的转换公式已经给定了,因此能下降复杂度的方法也就是从计算顺序等方面着手。编码
下降时间复杂度方法:spa
hashcode(“abcd”) = (ascii(a) * 333 + ascii(b) * 332 + ascii(c) *33 + ascii(d)) % HASH_SIZEcode
来讲,其实彻底能够对每一项先取余再相加(能除就尽可能先除),这样能够减小内存占用和计算量。对象
改进后的程序:内存
class Solution:
""" @param key: A string you should hash @param HASH_SIZE: An integer @return: An integer """
def hashCode(self, key, HASH_SIZE):
# write your code here
n = len(key)
num = 0
temp = 1
for i in range(n-1,-1,-1):
num += ord(key[i])*temp%HASH_SIZE
temp = temp*33 % HASH_SIZE
num = num % HASH_SIZE
return num
复制代码