454.四数相加II 、383. 赎金信 、15. 三数之和 、18. 四数之和
- 454.四数相加II:
题目:四数相加
解题:
1)将四个数组两两分为一组。将前两个数组的sum和各自的个数用一个map存下来。
2)然后遍历后两个数组的-(sum),看是否存在在map中
3)这样是两个复杂度为n的平方的循环的叠加,因此整体复杂度也是
代码:
class Solution(object):
def fourSumCount(self, nums1, nums2, nums3, nums4):
"""
:type nums1: List[int]
:type nums2: List[int]
:type nums3: List[int]
:type nums4: List[int]
:rtype: int
"""
sumab = dict()
count = 0
for num1 in nums1:
for num2 in nums2:
if num1 + num2 not in sumab:
sumab[num1 + num2] = 1
else:
sumab[num1 + num2] += 1
for num3 in nums3:
for num4 in nums4:
if -(num3 + num4) in sumab.keys():
count += sumab[-(num3 + num4)]
return count
- 383赎金信:
题目:赎金信
解题:
easy,就是创建一个字典然后查找它的键值
代码:
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
dictA = dict()
for a in magazine:
if a not in dictA:
dictA[a] = 1
else:
dictA[a] += 1
for b in ransomNote:
if b not in dictA.keys():
return False
else:
dictA[b] -= 1
if dictA[b] < 0:
return False
return True
- 15三数之和:
题目:
解题:
1)这题思维上还挺复杂的。首先要选择双指针思路而非哈希表。因为题目中有去掉重复的条件,采用哈希表的去重很麻烦容易错。本题采用第一个for循环来寻找第一个数值,双指针表示后两个值所在位置。
2)双指针操作首先要对数组进行排序,像两数之和那样的需要返回数组原下标的题目就不能用这种方法了。
3)left和right指针的移动有讲究。一定要先将等于0的三元组放入res数组中,然后再移动这两个指针。并且在这个条件中,一次可以同时left和right这两个指针,因为在已经去重的条件下,只移动一个指针不可能再为0
4)去重操作有讲究。 对于这三个指针都需要做去重。第一个指针的去重位置和第二三个指针位置不同。
代码:
nums = sorted(nums)
res = []
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:#对第一个指针去重,如果当前指针和上一个值一样则继续向后移动
continue
if nums[i] > 0:#第一个值大于0则
break
left = i + 1
right = len(nums) - 1
while left < right:
if nums[i] + nums[left] + nums[right] >0:
right -= 1
elif nums[i] + nums[left] + nums[right] < 0:
left += 1
else:
res.append([nums[i],nums[left],nums[right]])
left += 1
while left < right and nums[left] == nums[left - 1]:
left += 1
right -= 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
return res
- 18四数之和 :