一、454.四数相加
对题目的看法:由于只想到使用四个for循环暴力求解,故看卡哥的视频,发现可以与第六天的两个一样建立字典来解决。代码如下:
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
haxi = dict()
for i in nums1:
for j in nums2:
if i+j in haxi:
haxi[i+j] += 1
else:
haxi[i+j] = 1
desult = 0
for i in nums3:
for j in nums4:
if -(i+j) in haxi:
desult = desult +haxi[-(i+j)]
return desult
结果:
二、383. 赎金信
对题目的看法:想对 magazine 建立一个字典,value 是次数,对 ransomNote 进行遍历,如果字典的value有小于0的,则返回false,反正返回true.看了卡哥的之后可以用数组优化,条件可以改成==0.代码如下:
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
haxi = dict()
for i in magazine:
haxi[i] = haxi.get(i,0)+1
for i in ransomNote:
if i not in haxi or haxi[i] ==0 :
return False
else:
haxi[i] -= 1
return True
结果:
三、15. 三数之和
对题目的看法:思路不清晰故看卡哥视频,了解排序后用双指针。可得以下代码:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
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[left] ==nums[left+1]:
left +=1
while right>left and nums[right] == nums[right -1]:
right -= 1
right -=1
left += 1
return result
四、18. 四数之和
对题目的看法:通过卡哥给的思路运用双指针:
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
n = len(nums)
nums.sort()
result = []
for i in range(n):
if nums[i] >0 and target > 0 and nums[i] > target:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n):
if nums[i] + nums[j] > target and target > 0:
break
if j > i + 1 and nums[j] == nums[j - 1]:
continue
left, right = j + 1, n - 1
while left < right:
s = nums[i] + nums[j] + nums[left] + nums[right]
if s == 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 s < target:
left += 1
else:
right -= 1
return result
结果: