代码随想录算法训练营Day7
454.四数相加II
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
# Hash Map
# 2022.11.28
hashMap = dict()
for n1 in nums1:
for n2 in nums2:
if (n1+n2) in hashMap:
hashMap[n1+n2] += 1
else:
hashMap[n1+n2] = 1
count = 0
for n3 in nums3:
for n4 in nums4:
if (-n3-n4) in hashMap:
count += hashMap[-n3-n4]
return count
# TC: O(N**2)
# SC: O(N**2)
383.赎金信
使用HashArray:
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
# Hash Array
myArray = [0] * 26
for mm in magazine:
myArray[ord(mm) - ord("a")] += 1
for ss in ransomNote:
myArray[ord(ss) - ord("a")] -= 1
for ii in myArray:
if ii < 0:
return False
return True
15.三数之和
双指针可以使时间复杂度 divide by N (本题中由O(N的3次方)下降为O(N的平方)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
# 提示哈希表边界复杂,使用双指针
nums.sort()
res = []
n = len(nums)
for ii in range(n):
if (ii and nums[ii] == nums[ii-1]): continue
jj = ii + 1
kk = n - 1
while (jj < kk):
if nums[jj] + nums[kk] == -nums[ii]:
res.append([nums[ii],nums[jj],nums[kk]])
while (jj < kk and nums[jj] == nums[jj+1]): jj += 1
while (jj < kk and nums[kk] == nums[kk-1]): kk -= 1
jj += 1
kk -= 1
elif nums[jj] + nums[kk] < -nums[ii]:
jj += 1
elif nums[jj] + nums[kk] > -nums[ii]:
kk -= 1
return res
# TC: O(N logN)
# SC: O(N)
18. 4Sum
重做:进阶在第一层和第二层考虑剪枝
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
# 仿照3sum的思路
nums.sort()
res = []
n = len(nums)
for aa in range(n):
if aa and nums[aa] == nums[aa-1]: continue
for bb in range(aa+1, n):
if (bb-1) and nums[bb] == nums[bb-1]: continue # (bb-1) 这里出现错误
cc = bb + 1
dd = n - 1
while cc < dd:
if nums[cc] + nums[dd] == target - nums[aa] - nums[bb]:
res.append([nums[aa], nums[bb], nums[cc], nums[dd]])
while cc < dd and nums[cc] == nums[cc+1]: cc += 1
while cc < dd and nums[dd] == nums[dd-1]: dd -= 1
cc += 1
dd -= 1
elif nums[cc] + nums[dd] < target - nums[aa] - nums[bb]:
cc += 1
else:
dd -= 1
return res
# TC: O(N**3)
# SC: O(N)
# 进阶在第一层和第二层考虑剪枝