哈希算法
- 什么是哈希:哈希及哈希的原理
- 两个数的和:快速寻找两个数的和
- 单词模式匹配:简单的模式匹配问题
一.两个数的和
from IPython.display import Image
Image(filename="./data/3_01.png",width=800,height=960)
![output_3_0.png](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4ubmxhcmsuY29tL3l1cXVlLzAvMjAxOS9wbmcvMjE0NDM4LzE1NTk5MTQ5ODczODgtNTBhZWUzMWUtMTY4NS00YmY1LTg3MTUtMDk2MzNhNWNjMWNkLnBuZw?x-oss-process=image/format,png#align=left&display=inline&height=3968&name=output_3_0.png&originHeight=3968&originWidth=2976&size=3230821&status=done&width=2976)
原始方法
def twoSum(nums,target):
res=[]
newnums=nums[:]
newnums.sort()
left=0
right=len(newnums)-1
while left<right:
if newnums[left]+newnums[right]==target:
for i in range(0,len(nums)):
if nums[i]==newnums[left]:
res.append(i)
break
for i in range(len(nums)-1,-1,-1):
if nums[i]==newnums[right]:
res.append(i)
break
res.sort()
break
elif newnums[left]+newnums[right]<target:
left=left+1
elif newnums[left]+newnums[right]>target:
right=right-1
return (res[0]+1,res[1]+1)
nums=[3,7,10,4,5]
target=11
twoSum(nums,target)
(2, 2)
哈希算法
def twoSum(nums,target):
dict={}
for i in range(len(nums)):
m=nums[i]
if target-m in dict:
return (dict[target-m]+1,i+1)
dict[m]=i
twoSum(nums,target)
(2, 4)
三.单词模式匹配
def wordPattern(wordPattern,input):
word=input.split(" ")
if len(word)!=len(wordPattern):
return False
hash={}
used={}
for i in range(len(wordPattern)):
if wordPattern[i] in hash:
if hash[wordPattern[i]]!=word[i]:
return False
else:
if word[i] in used:
return False
hash[wordPattern[i]]=word[i]
used[word[i]]=True
return True
三.猜词游戏
Image(filename="./data/3_02.png",width=800,height=960)
![output_13_0.png](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4ubmxhcmsuY29tL3l1cXVlLzAvMjAxOS9wbmcvMjE0NDM4LzE1NTk5MTQ5OTQ5NTktOGI3MDljYzItOTUwMS00N2EzLWIyMzYtOGE1ZGM1ZGIzMzQwLnBuZw?x-oss-process=image/format,png#align=left&display=inline&height=3968&name=output_13_0.png&originHeight=3968&originWidth=2976&size=2994107&status=done&width=2976)
def getHint(secret,guess):
secret_dict={}
guess_dict={}
A=0
B=0
for i in range(len(secret)):
if secret[i]==guess[i]:
A+=1
else:
if secret[i] in secret_dict:
secret_dict[secret[i]]=secret_dict[secret[i]]+1
else:
secret_dict[secret[i]]=1
if guess[i] in guess_dict:
guess_dict[guess[i]]=guess_dict[guess[i]]+1
else:
guess_dict[guess[i]]=1
for digit in secret_dict:
if digit in guess_dict:
B+=min(secret_dict[digit],guess_dict[digit])
return str(A)+"A"+str(B)+"B"
secret="1123"
guess="9111"
getHint(secret,guess)
'1A1B'