博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode18. 4Sum
阅读量:4221 次
发布时间:2019-05-26

本文共 2085 字,大约阅读时间需要 6 分钟。

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 collectionsimport itertoolsclass 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

转载地址:http://twqmi.baihongyu.com/

你可能感兴趣的文章
游戏设计的艺术:一本透镜的书——第十三章 玩家通过界面玩游戏
查看>>
编写苹果游戏中心应用程序(翻译 1.3 为iOS应用程序设置游戏中心)
查看>>
编写苹果游戏中心应用程序(翻译 1.4 添加游戏工具包框架)
查看>>
编写苹果游戏中心应用程序(翻译 1.5 在游戏中心验证本地玩家)
查看>>
编写苹果游戏中心应用程序(翻译 1.6 获取本地玩家的信息)
查看>>
编写苹果游戏中心应用程序(翻译 1.7 在游戏中心添加朋友)
查看>>
编写苹果游戏中心应用程序(翻译 1.8 获取本地玩家的好友信息)
查看>>
WebGL自学教程《OpenGL ES 2.0编程指南》翻译——勘误表
查看>>
WebGL自学教程——WebGL示例:12. 要有光
查看>>
WebGL自学教程——WebGL示例:13.0 代码整理
查看>>
WebGL自学教程——WebGL示例:14.0 代码整理
查看>>
恶心的社会
查看>>
中国式危机公关9加1策略(第五章 慎用信息控制策略)
查看>>
展现自己的人生智慧
查看>>
深入理解java多态性
查看>>
Java新手进阶:细说引用类型
查看>>
osg中使用MatrixTransform来实现模型的平移/旋转/缩放
查看>>
(一) Qt Model/View 的简单说明
查看>>
(二)使用预定义模型 QStringListModel例子
查看>>
UVM:7.4.5 加入存储器
查看>>