20 leetcode - 4Sum

建议先看3Sum,然后更容易理解4Sum.
3Sum链接http://blog.youkuaiyun.com/lis_12/article/details/53207418

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
举例:
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]
'''
class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        length = len(nums)    
        if length < 4:
            return []
        nums.sort() #先排序
        result = []

        for index1,val1 in enumerate(nums[:-3]):
            if index1 > 0 and nums[index1] == nums[index1 - 1]:
                continue
            for index2,val2 in enumerate(nums[index1 + 1:][:-2]):
                if index2 > 0 and nums[index1 + index2 + 1] == nums[index1 + index2]:
                    continue
                target2 = target - val1- val2
                first = index1 + index2 + 2
                second = length - 1
                while first < second:
                    if nums[first] + nums[second] == target2:
                        result.append([val1,val2,nums[first],nums[second]])
                        while first < second and nums[first] == nums[first + 1]:  #两个条件位置不能颠倒,不然可能会越界
                            first += 1
                        while first < second and nums[second] == nums[second - 1]:
                            second -= 1
                        first += 1
                        second -= 1
                    elif nums[first] + nums[second] < target2:
                        first += 1
                    else:
                        second -= 1
        return result


if __name__ == "__main__":
    s = Solution()
    print s.fourSum([0,0,0,0],0)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值