454.四数相加II
初步想法
只能想到暴力解法
题解
https://programmercarl.com/0454.%E5%9B%9B%E6%95%B0%E7%9B%B8%E5%8A%A0II.html
使用map或者set
A B C D四个整数数组,遍历AB,求出所有的a+b值,并用map存储a+b和a+b出现的次数,在遍历 C,D对每一个c+d判断0-(c+d)是否存在了map里
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
AB = dict()
count = 0
for i in nums1:
for j in nums2:
if i+j in AB:
AB[i+j] += 1
else:
AB[i+j] = 1
for i in nums3:
for j in nums4:
if 0-i-j in AB:
count += AB[0-i-j]
return count
总结
很巧妙,同时要注意这里需要做一个判断
if i+j in AB:
AB[i+j] += 1
else:
AB[i+j] = 1
383. 赎金信
初步想法
magazine的字符转换成map, key是字母,value是该字母在magazine出现的次数
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
hash = dict()
for i in magazine:
if i not in hash:
hash[i] = 1
else:
hash[i] += 1
for i in ransomNote:
if i in hash and hash[i] != 0:
hash[i] -= 1
else:
return False
return True
题解
https://programmercarl.com/0383.%E8%B5%8E%E9%87%91%E4%BF%A1.html
使用数组的更省空间
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))
15. 三数之和
初步想法
固定两个数,在数组中查找需要的第三个数是否存在
题解
https://programmercarl.com/0015.%E4%B8%89%E6%95%B0%E4%B9%8B%E5%92%8C.html
a+b+c
对数字进行排序
for loop控制指针i,对应a, left对应b,right对应c,
如果nums[i]+nums[left]+nums[right]>0 right –
如果<0 left++
如果 = 0,加入结果
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
for i in range(0,len(nums)):
if nums[i] > 0 :
return result # 因为已经排过序了
if i > 0 and nums[i] == nums[i-1]:
continue # i 与前一个重复了相当于a = num[i]已经被考虑过了,不用再考虑一遍了
left = i + 1
right = len(nums) - 1
while right > left:
if nums[i] + nums[left] + nums[right] > 0:
right -=1
elif nums[i] + nums[left] + nums[right] <0:
left +=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
right -= 1
left += 1
return result
18. 四数之和
初步想法
跟三数之和一样:
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
result = []
nums.sort()
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1,len(nums)):
if j > i + 1 and nums[j] == nums[j-1]:
continue
right = len(nums) - 1
left = j + 1
while left < right:
if nums[i] + nums[j] + nums[left] + nums[right] < target:
left += 1
elif nums[i] + nums[j] + nums[left] + nums[right] > target:
right -= 1
else:
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
return result
题解
https://programmercarl.com/0018.%E5%9B%9B%E6%95%B0%E4%B9%8B%E5%92%8C.html#%E8%A1%A5%E5%85%85