题目
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
思路
可以和之前3Sum的思路一样,采用快排,时间复杂度为O(N^3),但是很容易超时,所以这里采用另外一种方法,哈希表用空间换时间,以增加空间复杂度的代价来降低时间复杂度。首先建立一个字典dict,字典的key值为数组中每两个元素的和,每个key对应的value为这两个元素的下标组成的元组,元组不一定是唯一的。
如对于num=[1,2,3,2]来说,dict={3:[(0,1),(0,3)], 4:[(0,2),(1,3)], 5:[(1,2),(2,3)]}。
这样就可以检查target-key这个值在不在dict的key值中,如果target-key在dict中并且下标符合要求,那么就找到了这样的一组解。由于需要去重,这里选用set()类型的数据结构,即无序无重复元素集。最后将每个找出来的解(set()类型)转换成list类型输出即可。
代码
class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
numlen,res,adict = len(nums),set(),{}
# 如果输入数字不够直接返回空列表
if numlen < 4:
return []
# 构建哈希表,如对于num=[1,2,3,2]来说,dict={3:[(0,1),(0,3)], 4:[(0,2),(1,3)], 5:[(1,2),(2,3)]}
nums.sort()
for i in range(numlen):
for j in range(i+1,numlen):
if nums[i]+nums[j] not in adict:
adict[nums[i]+nums[j]] = [(i,j)]
else:
adict[nums[i]+nums[j]].append((i,j))
for i in range(numlen):
for j in range(i+1,numlen-2):
digit = target - nums[i] - nums[j]
if digit in adict:
for item in adict[digit]:
if item[0] > j:
res.add((nums[i],nums[j],nums[item[0]],nums[item[1]]))
return [list(k) for k in res]
运行结果
282 / 282 test cases passed.
Status: Accepted
Runtime: 160 ms