1、题目描述:
2、题解:
哈希表分为:哈希集合和哈希映射,此题可以用这两种方法去做。
哈希集合:
我们首先遍历一次,这次可以把猜中的次数统计出来(统计在同一位置上两者相等的次数),如果两个不相等,就加入哈希集合。(考虑到除了猜中的位置,其他位置可能出现重复的字符,因此不用集合,而是用数组的数据结构,我们也把它叫做哈希集合,其实叫哈希数组更贴切,但是为了统一记忆,我们还是叫做哈希集合)
然后再次遍历,统计除了猜中的位置,其他位置的伪猜中的次数。
也即是分别统计猜中和伪猜中的次数。
class Solution:
def masterMind(self, solution: str, guess: str) -> List[int]:
#哈希集合
res = [0 for _ in range(2)]
hashset = []
for i in range(4):
if solution[i] == guess[i]:
res[0] += 1
else:
hashset.append(solution[i])
for i in range(4):
if guess[i] != solution[i]:
if guess[i] in hashset:
res[1] += 1
hashset.remove(guess[i])
return res
哈希映射:
先统计猜中的次数,再统计猜中和伪猜中总的次数,然后两者相减就是伪猜中的次数。
第一次遍历统计猜中的次数,并且把sollution中的“字符:出现的次数”放在字典中(也就是哈希映射中)
再次遍历,统计猜中和伪猜中总的次数:如果guess中的字符在哈希映射中出现且value值大于0,那么就把total加1,相应的value减1.
最后输出结果[猜中的次数,猜中和伪猜中总的次数-猜中的次数]
class Solution:
def masterMind(self, solution: str, guess: str) -> List[int]:
#哈希映射
true = 0
total = 0
hashdict = {}
for i in range(4):
if solution[i] == guess[i]:
true += 1
if solution[i] not in hashdict:
hashdict[solution[i]] = 1
else:
hashdict[solution[i]] += 1
for i in range(4):
if guess[i] in hashdict and hashdict[guess[i]] > 0:
total += 1
hashdict[guess[i]] -= 1
return [true,total - true]
3、复杂度分析:
时间和空间复杂度都是O(1),因为数组的长度是常数。