今天来做哈希表part02 算是补昨天,因为昨天做的
第一题:454. 四数相加 II
第一道题,老是想用循环去解决问题,看了点拨才知道可以两两一组作为比较
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
a = {}
count = 0
for i in nums1:
for j in nums2:
if i+j not in a:
a[i+j] = 1
else:
a[i+j] += 1
for i in nums3:
for j in nums4:
if -(i+j) in a :
count += a[-(i+j)]
return count
第二题:383. 赎金信
第二题之前有做过,这次用哈希表试了一次,
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ran = {}
ransomNote = list(ransomNote)
magazine = list(magazine)
for i in ransomNote:
if i not in ran:
ran[i] = 1
else:
ran[i] += 1
for i in magazine:
if i not in ran:
continue
else:
ran[i] -= 1
print(ran)
for i in ran.values():
if i > 0:
return False
return True
第三题和第四题:因为题目类型是一样的,就放在一起讲了,主要是理解其中的思想,一开始想仿照今天的第一题454.两数相加去做,但是发现在去重的阶段太复杂了,所以看了卡哥的思想。感觉思路很好,四数相加就是再加一层for循环,对于去重条件改了一下,两道题都用了两个指针去写,可以有效降低时间复杂度
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
print(nums)
result = []
for i in range(len(nums)):
left = i+1
right = len(nums)-1
if i > 0 and nums[i] == nums[i-1]:
continue
while(left <right):
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
left += 1
right -= 1
return result
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
result = []
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
left = j + 1
right = len(nums)-1
while(left < right):
if nums[i] + nums[j] + nums[left] + nums[right] > target:
right -= 1
elif nums[i] + nums[j] + nums[left] + nums[right] < target:
left += 1
else:
result.append([nums[i], nums[j] , nums[left], nums[right]])
while(left<right and nums[right-1] == nums[right]):
right -= 1
while(left<right and nums[left] == nums[left+1]):
left += 1
right -= 1
left += 1
return result
总结:今天的一和三四都有必要再复习一下,十分像但是用的办法又不太一样,所以加油!!温故而知新!!