這道題沒有什麼算法難點,公式已經給出了,重點是一些函數的使用和時間複雜度的問題。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
複製代碼