学习资料:https://programmercarl.com/0015.三数之和.html#其他语言版本
学习记录:
454.四数相加(hash_dict,前两个数一组遍历a+b,后两个数一组遍历找0-(a+b))
点击查看代码
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hash_map = dict()
for i in nums1:
for j in nums2:
key=i+j
hash_map[key]=hash_map.get(key, 0)+1
count = 0
for i in nums3:
for j in nums4:
key=0-(i+j)
if key in hash_map:
count += hash_map[key]
return count
点击查看代码
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ran_list = [0]*26
mag_list = [0]*26
for i in ransomNote:
index= ord(i)-ord('a')
ran_list[index] += 1
for i in magazine:
index = ord(i)-ord('a')
mag_list[index] += 1
for i in range(26):
if ran_list[i]<=mag_list[i]:
pass
else:
return False
return True
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = []
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
return result
# 第一次去重
if i > 0 and nums[i] == nums[i-1]:
continue
# 双指针
left = i + 1
right = len(nums)-1
while right > left:
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 right>left and nums[right]==nums[right-1]:
right -= 1
while right>left and nums[left]==nums[left+1]:
left += 1
left += 1
right -= 1
return result
PS:18题明天再做吧,假期结束啦,今天吃土豆烧排骨、甜椒炒肉、糖醋莲白,幸福~~~
标签:四数,15,nums,int,List,随想录,right,hash,left From: https://www.cnblogs.com/tristan241001/p/18449385