代码随想录 - Day9 - 哈希表
因为一个考试失利所以荒废了快一个月时间,重新开始继续做题吧
438. 找到字符串中所有字母异位词
第一版代码
自我感觉逻辑没问题,意料之中的超时了
res = []
table = [0] * 26
temp = [0] * 26
count = 0
for i in range(len(p)):
table[ord(p[i]) - ord('a')] += 1
for left in range(len(s)):
for right in range(len(p)):
if left + right < len(s):
temp[ord(s[left + right]) - ord('a')] += 1
count += 1
if temp == table:
res.append(left)
temp = [0] * 26
count = 0
if count == len(p):
temp = [0] * 26
count = 0
return res
参考了别人的题解
先排除掉特殊情况len(p) >= len(s)
然后每增加一个字母,就去掉最前面的字母,temp == table
时则把起始下标保存到res
里。用滑动窗口解决该题
if len(p) > len(s):
return []
res = []
table = [0] * 26
temp = [0] * 26
for i in range(len(p)):
table[ord(p[i]) - ord('a')] += 1
temp[ord(s[i]) - ord('a')] += 1
if temp == table:
res.append(0)
for position in range(len(p), len(s)):
temp[ord(s[position - len(p)]) - ord('a')] -= 1
temp[ord(s[position]) - ord('a')] += 1
if temp == table:
res.append(position - len(p) + 1)
return res
349. 两个数组的交集
- 直接用
set()
函数
set1 = set(nums1)
set2 = set(nums2)
a = []
for i in set1:
if i in set2:
a.append(i)
return a
- 不使用
set()
函数
table = {}
res = []
for i in nums1:
table[i] = 1
for i in nums2:
if i in table.keys() and table[i] == 1:
res.append(i)
table[i] = 0
return res
350.两个数组的交集 II
和上一题思路一致
res = []
table = {}
for i in nums1:
if i not in table:
table[i] = 0
table[i] += 1
for i in nums2:
if i in table.keys() and table[i] > 0:
res.append(i)
table[i] -= 1
return res
202. 快乐数
自己写的代码,没考虑到无限循环,没想到啊
res = 0
while n * n > 9:
n = str(n)
res = 0
for i in range(len(n)):
res += int(n[i]) * int(n[i])
n = res
if n == 1:
return True
return False
看题解之后秒懂,想找出循环就用哈希表记录一下,加一个判断条件
res = 0
table = {}
while n * n > 9:
if n not in table:
table[n] = 0
else:
break
table[n] = 1
n = str(n)
res = 0
for i in range(len(n)):
res += int(n[i]) * int(n[i])
n = res
if n == 1:
return True
return False
1. 两数之和
- 暴力解法,两层for循环
- 用哈希表记录,在python里这里用到字典
dict
。每次在表里查找是否出现target - value
对应的整数,若出现则返回结果
records = {}
for index, value in enumerate(nums):
if target - value in records:
return [records[target - value], index]
records[value] = index
return
454. 四数相加 II
两两组合求解,解法与两数之和类似
table = {}
for i in nums1:
for j in nums2:
if i + j not in table:
table[i + j] = 0
table[i + j] += 1
count = 0
for i in nums3:
for j in nums4:
if 0 - (i + j) in table:
count += table[0 - (i + j)]
return count
今天就先到这