454.四数相加II
python的解法内可以用到defaultdict
Python中的defaultdict方法
python中的dict是一个重要的数据类型,知道如何使用这个数据类型很简单,但是这个类型使用过程中容易进入一些误区,这篇文章主要对defaultdict方法的讲解,深入的了解dict数据类型。
字典(dictionary)数据类型,不同于其他由数字索引的序列,字典是用”键”(key)来索引的。通常表示为dict(key: val, …),有以下特征:
- 键可以是任何不可变(immutable)数据类型(不可变数据类型:数字,字符串、元组)(也就是说key不能为列表和字典类型);
- 每个键必须是唯一的;
- 字典中每一项的顺序是任意的;
1,collections.defaultdict类的介绍:
defaultdict是Python内建dict类的一个子类,第一个参数为default_factory
属性提供初始值,默认为None。它覆盖一个方法并添加一个可写实例变量。它的其他功能与dict相同,但会为一个不存在的键提供默认值,从而避免KeyError异常。
2,一般的dict类型会导致KeyError异常:
一般dict类型:
KeyError异常:
defaultdict类避免KeyError异常:
3,collections.defaultdict类使用:
类型名称作为初始化函数参数:这个就是上面的例子。可调用函数作为初始化函数参数:
文章转载:Python中的defaultdict方法 - 知乎
class Solution(object):
def fourSumCount(self, nums1, nums2, nums3, nums4):
# 使用字典存储nums1和nums2中的元素及其和
hashmap = dict()
for n1 in nums1:
for n2 in nums2:
if n1 + n2 in hashmap:
hashmap[n1+n2] += 1
else:
hashmap[n1+n2] = 1
# 如果 -(n1+n2) 存在于nums3和nums4, 存入结果
count = 0
for n3 in nums3:
for n4 in nums4:
key = - n3 - n4
if key in hashmap:
count += hashmap[key]
return count
15. 三数之和
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = []
nums.sort()#这是啥
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[right] == nums[right -1]:
right -= 1
while right > left and nums[left] == nums[left + 1]:
left += 1
right -= 1
left += 1
return result
18. 四数之和
from typing import List
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
n = len(nums)
result = []
for i in range(n):
if nums[i] > target and nums[i] > 0 and target > 0:# 剪枝(可省)
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