242.有效的字母异位值(使用了数组)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
record=[0]*26
for i in s:#ord转换为ASCII值
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.两个数组的交集
直接使用set 不仅占用空间比数组大,而且速度要比数组慢,set把数值映射到key上都要做hash计算的。数量大的时候才用set
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)#集合的add函数
del table[num]#节省空间
return list(res)#返回列表形式
使用数组
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
#使用数组
count1=[0]*1001
count2=[0]*1001
result=[]
for i in range(len(nums1)):
count1[nums1[i]]+=1
for i in range(len(nums2)):
count2[nums2[i]]+=1
for k in range(1001):
if count1[k]*count2[k]>0:
result.append(k)
return result
202.快乐数
对取数值各个位上的单数操作要熟悉
class Solution:
def isHappy(self, n: int) -> bool:
record=set()
while n not in record:
record.add(n)
n_str=str(n)#把n转换为字符串
new_sum=0#用来存储
for i in n_str:
new_sum+=int(i)**2
if new_sum==1:
return True
else:
n=new_sum
return False#无限循环跳出while但也表示始终变不到一
快慢指针
class Solution:
def isHappy(self, n: int) -> bool:
#快慢指针
slow=n
fast=n
while self.get_sum(fast)!=1 and self.get_sum(self.get_sum(fast)):
slow=self.get_sum(slow)
fast=self.get_sum(self.get_sum(fast))
if slow==fast:
return False#无限循环但始终变不到1
return True#出现等于1
def get_sum(self,n: int) ->int:
new_sum=0
while n:
n,r=divmod(n,10)#循环将个位数取出,如取出个位十位变个位,divmod返回商和余数
new_sum+=r**2
return new_sum
1.两数之和
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
map_a = dict()
k = len(nums)
for i, num in enumerate(nums):
if target - num in map_a:
return [map_a[target - num], i]
map_a[nums[i]] = i