**18. 4Sum 四树数之和

1. 原始题目

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

示例:

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

2. 分析

四数之和暴力为4次方,因此可以利用哈希表,将其转为平方复杂度!

思路是每次循环以两数之和为键,以其下标为值放到哈希表中。然后对于新来的一对数要判断是否有解在其中,有的话将其遍历并判断是否重复后放到结果中。

 

3. 解法

 1 from collections import defaultdict
 2 class Solution:
 3     def fourSum(self, nums, target: int):
 4         res = []
 5         if len(nums)<4:return res
 6         temp = defaultdict(list)          # 建立默认字典,值为列表
 7         for i in range(len(nums)):
 8             for j in range(i+1,len(nums)):           # j从i之后遍历就好
 9                 temp[nums[i]+nums[j]].append((i, j))    # 注意存放的是当前的索引对
10                 component = target-nums[i]-nums[j]      # 存放后看看是否已有满足当前目标的样本对 
11                 if (component in temp):                 # 如果有满足当前目标的样本对 
12                     for p,q in temp[component]:         # 将每种可能性都拿出来判断
13                         if (len(set([p,q,i,j]))==4):    # 保证是4个不同的索引!去重复   
14                             idx = [p,q,i,j]
15                             if sorted([nums[t] for t in idx]) not in res:    # 判断当前序列是否已经有了,没有则添加
16                                 res.append(sorted([nums[t] for t in idx])) 
17                     
18         return res

 

posted @ 2019-05-10 11:35  三年一梦  阅读(184)  评论(0)    收藏  举报