242.有效的字母异位词
题目:
![](https://i-blog.csdnimg.cn/blog_migrate/80228e2af105752af7db074e560a440d.png)
思路:
使用哈希表(散列表)来记录字符串的元素。只需要把字符映射到数组也就是哈希表的索引下标上,因为字符a到字符z的ASCII是26个连续的数值,所以字符a-z映射为下标0-25。遍历字符串s时,只需要将record数组中对应的值+1。遍历t,只需要将对应的值-1。最后查看record中数组的元素是否都为0,如果存在不是0的元素,则输出false,若都是0则输出true。
代码:
def isAnagram(self, s: str, t: str) -> bool:
record = [0]*26
for i in s:
record[ord(i) - ord("a")] += 1
for i in t:
record[ord(i) - ord("a")] -= 1
for i in range(26):
if record[i] != 0:
return False
return True
349. 两个数组的交集
题目:
![](https://i-blog.csdnimg.cn/blog_migrate/e784b380a83d86e30fdd96cc51658785.png)
思路:
python中可以用字典来存放,将nums1中出现的值设定为键,对应的值为1,若nums2中的值是字典中的键,且值为1则说明是两个数组的交集,若值为0,则是重复的值。
代码:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
ans = []
dict = {}
for num in nums1:
dict[num] = 1
for num in nums2:
if num in dict.keys() and dict[num] == 1:
ans.append(num)
dict[num] = 0
return ans
写这里的时候遇到一个问题,python中判断语句的时间复杂度是多少?
python中常用in来判断一个元素是否在list中,判断的时间复杂度为:
in list : o(n)
in set : o(1)
in dict : o(1)
python中set来做更简单:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
文章参考:
字典:Python 字典用法详解(超全) - 知乎 (zhihu.com)
关于python中list和set:
(2条消息) Python中list和set的区别_Python热爱者的博客-CSDN博客_python list set
python中list的存放方式:
(2条消息) 最终总结 python中 list 到底是怎么实现的,内存里面是怎么存放的_中南自动化学院“智能控制与优化决策“至渝的博客-CSDN博客_python列表内存机制
202. 快乐数
题目:
![](https://i-blog.csdnimg.cn/blog_migrate/29300403a4de790aa77d655e6e41b575.png)
思路:题目的关键是说了如果不是快乐数寻找的过程就会无限循环,说明sum会重复出现,如果不会重复出现说明是快乐数,那么一直找找到sum=1为止
代码:
def isHappy(self, n: int) -> bool:
record = set()
def calculate(num):
sum = 0
while num:
tmp = num % 10
sum = sum + tmp * tmp
num = num // 10
return sum
while True:
sum = calculate(n)
if sum == 1:
return True
elif sum in record:
return False
else:
record.add(sum)
n = sum
1. 两数之和
题目:
![](https://i-blog.csdnimg.cn/blog_migrate/bae760c4a30c88dc1ec1382ef02729b6.png)
思路:
什么时候使用哈希法?
当我们需要查询一个元素是否出现过,或者一个元素是否在集合里的时候,就要第一时间想到哈希法。
本题呢,我就需要一个集合来存放我们遍历过的元素,然后在遍历数组的时候去询问这个集合,某元素是否遍历过,是否出现在这个集合。那么我们就应该想到使用哈希法了。
因为本地,我们不仅要知道元素有没有遍历过,还有知道这个元素对应的下标,需要使用 key value结构来存放,key来存元素,value来存下标,那么使用map正合适。
再来看一下使用数组和set来做哈希法的局限。
数组的大小是受限制的,而且如果元素很少,而哈希值太大会造成内存空间的浪费。
set是一个集合,里面放的元素只能是一个key,而两数之和这道题目,不仅要判断y是否存在而且还要记录y的下标位置,因为要返回x 和 y的下标。所以set 也不能用。
此时就要选择另一种数据结构:map ,map是一种key value的存储结构,可以用key保存数值,用value在保存数值所在的下标。
代码:
def twoSum(self, nums: List[int], target: int) -> List[int]:
ans = []
record = {}
for index,value in enumerate(nums):
if (target - value) in record:
return [record[target - value],index]
else:
record[value] = index
enumerate函数介绍:
Python enumerate() 函数 | 菜鸟教程 (runoob.com)
文章参考: