454 四数相加 II
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hashmap=dict()
for n1 in nums1:
for n2 in nums2:
t=n1+n2
if t in hashmap:
hashmap[t]+=1
else:
hashmap[t]=1
ret=0
for n3 in nums3:
for n4 in nums4:
need=0-(n3+n4)
if need in hashmap:
ret+=hashmap[need]
return ret
383 赎金信
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
temp=[0]*26
for a in magazine:
temp[ord(a)-97]+=1
for a in ransomNote:
if temp[ord(a)-97]==0:
return False
else:
temp[ord(a)-97]-=1
return True
15 三数之和
def threeSum(self, nums: List[int]) -> List[List[int]]:
ret=[]
nums.sort()
for i in range(len(nums)):
l=i+1
r=len(nums)-1
if nums[i]>0:
break
if i>0 and nums[i]==nums[i-1]:
continue
while l<r:
t=nums[i]+nums[l]+nums[r]
if t>0:
r-=1
elif t<0:
l+=1
else:
ret.append([nums[i],nums[l],nums[r]])
while l!=r and nums[l]==nums[l+1]:
l+=1
while l!=r and nums[r]==nums[r-1]:
r-=1
l+=1
r-=1
return ret
18 四数之和
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
hashmap=dict()
for i in nums:
if i in hashmap:
hashmap[i]+=1
else:
hashmap[i]=1
ans=set()
for i in range(len(nums)):
for j in range(i+1,len(nums)):
for k in range(j+1,len(nums)):
val=target-nums[i]-nums[j]-nums[k]
if val in hashmap:
t=(nums[i]==val)+(nums[j]==val)+(nums[k]==val)
if t<hashmap[val]:
ans_temp=tuple(sorted([nums[i],nums[j],nums[k],val]))
ans.add(ans_temp)
else:
continue
return list(ans)