454.四数相加II
两个两个遍历的时间复杂度更低,1,3分是()
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hashmap=dict()#使用字典
for i in nums1:
for j in nums2:
if i + j in hashmap:#如果在哈希表内则值加一
hashmap[i+j]+=1
else:
hashmap[i+j]=1
count=0
for i in nums3:
for j in nums4:
key=-i-j
if key in hashmap:
count+=hashmap[key]#注意,不是i和j
return count
383.赎金信
用数组消耗的空间更小
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
#使用数组
ransom_count=[0]*26
magazine_count=[0]*26
for c in ransomNote:
ransom_count[ord(c)-ord('a')]+=1
for c in magazine:
magazine_count[ord(c)-ord('a')]+=1
return all(ransom_count[i] <= magazine_count[i] for i in range(26))#即当所有满足条件时才返回TRUE
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
#使用字典
counts={}
for c in magazine:
counts[c]=counts.get(c,0)+1#这行代码的作用是将字典counts中键为c的值加1。如果counts中不存在键为c的项,则将其添加到字典中,并将其值初始化为0,然后加1。
for c in ransomNote:
if c not in counts or counts[c]==0:
return False
counts[c]-=1#
return True
15.三数之和
我们要做的是 不能有重复的三元组,但三元组内的元素是可以重复的
双指针法一定要排序
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result=[]
nums.sort()#双指针法必须有序
for i in range(len(nums)):
if nums[i]>0:#如果第一个元素大于0,不需要再进一步检查
return result
if i >0 and nums[i]==nums[i-1]:#跳过相同的元素以避免重复
continue
left=i+1
right=len(nums)-1
while left<right:#不取等于,等于时相当于一个元素
sum_=nums[i]+nums[left]+nums[right]
if sum_<0:
left+=1
elif sum_>0:
right-=1
else:
result.append([nums[i],nums[left],nums[right]])
while(left<right and nums[left]==nums[left+1]):#去重
left+=1
while(left<right and nums[right]==nums[right-1]):
right-=1
right-=1
left+=1
return result
18.四数之和
四数之和这道题目 target是任意值
之前我们讲过哈希表的经典题目:454.四数相加II (opens new window),相对于本题简单很多,因为本题是要求在一个集合中找出四个数相加等于target,同时四元组不能重复
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
result=[]
for i in range(len(nums)):
if nums[i]>target and nums[i]>0 and target>0:
break
if i >0 and nums[i]==nums[i-1]:#去重,注意i》0
continue
for j in range(i+1,len(nums)):
if nums[i]+nums[j]>target and target>0:#因为已经有序,排在后面的一定更大,不可能再回到target
break
if j>i+1 and nums[j]==nums[j-1]:
#去重
continue
left,right=j+1,len(nums)-1
while left<right:
sum_=nums[i]+nums[j]+nums[left]+nums[right]
if sum_==target:
result.append([nums[i],nums[j],nums[left],nums[right]])
while left<right and nums[left]==nums[left+1]:#不回头
left+=1
while left<right and nums[right]==nums[right-1]:
right-=1
left+=1
right-=1#不要漏了
elif sum_<target:
left+=1
else:
right-=1
return result