58. 四数之和

58. 四数之和

中文English

给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。

样例

例1:

输入:[2,7,11,15],3
输出:[]

例2:

输入:[1,0,-1,0,-2,2],0
输出:
[[-1, 0, 0, 1]
,[-2, -1, 1, 2]
,[-2, 0, 0, 2]]

注意事项

四元组(a, b, c, d)中,需要满足a <= b <= c <= d

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

输入测试数据 (每行一个参数)如何理解测试数据?
背向型双指针:先固定两个值,然后里面嵌套一个两数之和
class Solution:
    """
    @param numbers: Give an array
    @param target: An integer
    @return: Find all unique quadruplets in the array which gives the sum of zero
    """
    def fourSum(self, numbers, target):
        # write your code here
        #相当于是两个两数之和
        length, res = len(numbers), []
        
        numbers = sorted(numbers)
        
        #固定前面两个值
        for i in range(3, length):
            #如果是相等的话,则跳过处理
            for j in range(2, i):
                total = target - numbers[i] - numbers[j]
                
                #剩下的两个进行求和,满足total
                left, right = 0, j - 1 
                while left < right:
                    sum = numbers[left] + numbers[right]
                    if sum == total:
                        #判断是否已经存在res里面
                        add_res = [numbers[left], numbers[right], numbers[j], numbers[i]]
                        if add_res not in res:
                            res.append(add_res)
               #right和left继续走,一个减小一个增大,继续查看是否还有没有满足条件的sum right
-= 1 left += 1 elif sum > total: right -= 1 elif sum < total: left += 1 return res

 

 

posted @ 2020-06-26 20:49  风不再来  阅读(89)  评论(0编辑  收藏  举报