242.有效的字母异位词
- 字母表和下标的转换:record[ord(i)-ord(‘a’)]
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
# 存储26位字母表
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. 两个数组的交集
- 字典和集合
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
# 使用哈希表存储一个数组中的所有元素
table = {}
for num in nums1:
table[num] = table.get(num, 0) + 1
# 使用集合存储结果
res = set()
for num in nums2:
if num in table:
res.add(num)
del table[num]
return list(res)
- 集合
return list(set(nums1) & set(nums2))
202. 快乐数
- 使用集合或者数组
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
record=[]
while n not in record:
record.append(n)
sum=0
for i in str(n):
sum+=int(i)**2
if sum==1:
return True
else:
n=sum
return False
python中的字典/集合/列表
dict字典
a=dict([key1, value1],[key2, value2])
a={}
a[key1]=value1
a[key2]=value2
a={x: x**2 for x in [1,2,3]}
- 索引:
dict1[key]
或者dict1.get(key
- 遍历:
for i in dict1:
for key, value in dict1.items():
for key in dict1.keys():
- 排序
- 先转成list,再sort
D={'a':1, 'b':2} D1=list(D.keys()) D1.sort() for i in D1: print(i, D[i])
- 使用内置sorted函数
for i in sorted(D): print(i,D[i])
set集合
集合可以看作是没有值的字典,其元素不重复,通过将list或其他类型的数据转换成集合可以过滤掉重复元素
s={'a','b','c'}
s=set(['a','b','c'])
# 用{}创建的是空字典,不是空集合
s=set()
{x**2 for x in 'abc'}
- 集合运算
s1 & s2
s1 | s2
s1 - s2
- 集合操作
set1.add('x') #添加元素。注意:集合中只能包含可哈希的对象,即list,dict都不能嵌入到集合中
set1.union(...) #取并集,效果等同于 | ,但是括号里可以是list,tuple,其他dict甚至是dict
set1.intersection(...) #取交集,同上
set1.issubset(set2) #判断set1是否是set2的子集
list列表
a=[1,2,3]
a[1:2]
- 删除元素
del(list1[index])
list1.pop(index)
list1.remove(value)
list1.clear()
list1[2:]=[]
- 拼接
list1+list2
list1.extend(list2)
- 插入元素
list1.append(value)
list1.insert(index,data)
list1.extend([2,3])
- 反转
list1.reverse()
- 计算指定元素x的个数
list1.count(x)
- 查找
list1.index(value)
- 复制
list2=list1.copy()
- 排序
list1=[(1,6),(3,4),(2,5)]
list1.sort(key=lambda x:x[1], reverse=True)
# 根据第二个元素,降序排列
sorted函数有返回值