leetcode18. 4Sum

136 篇文章 0 订阅

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:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
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)

思路:
土一点的解法就是一个一个判断,让四个加起来的和等于target。。然而这样太土了,python表示又TLE啦~~~

class Solution(object):
    def fourSum(self, nums, target):
        ans=[]
        if len(nums)>=4:
            for i in range(len(nums)-4):
                for j in range(i+1,len(nums)):
                    for k in range(j+1,len(nums)):
                        for l in range(k+1,len(nums)):
                            if nums[i]+nums[j]+nums[k]+nums[l]==target:
                                temp=sorted([nums[i],nums[j],nums[k],nums[l]])
                                if temp not in ans:
                                    ans.append(temp)
        return ans

好看一点的解法就是,两两求和,存在一个字典里面,key=两数之和,其value存储了该数的对应下标。
用到的函数
enumeration()可以遍历数组,以及返回其下标

for i in enumerate([5,7]):
    print i
(0,5)(1,7

itertools.combinations( XX ,2)函数
随机取两个数且不重复
即ab,ba视为ab

a=isdisjoin(b):a元素和b元素的交集为空集,则返回为True

python代码:

import collections
import itertools
class Solution:
    def fourSum(self,nums,target):
        doc=collections.defaultdict(list)
        ans=[]
        for (id1,val1),(id2,val2) in itertools.combinations(enumerate(nums),2):
            doc[val1+val2].append({id1,id2})
        keys=doc.keys()
        for key in keys:
            if doc[key] and doc[target-key]:
                for part1 in doc[key]:
                    for part2 in doc[target-key]:
                        if part1.isdisjoint(part2):
                            temp=sorted([nums[i] for i in part1 | part2])
                            if temp not in ans:
                                ans.append(temp)
                del doc[key]
                if key!=target-key:
                    del doc[target-key]
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值