Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.

Example:

Given array nums = [, , -, , -, ], and target = .

A solution set is:
[
[-, , , ],
[-, -, , ],
[-, , , ]
]

思路


  在看到这道题之后,我第一反应是使用之前求三数之和那样求四数之和,结果也是可行,但是运行结果显示的时间复杂度太高。这里我先将我自己的解决思路写下来

  时间复杂为O(n3),空间复杂为O(1)。

解决代码


 class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
if len(nums) < : # 异常情况,小于四个直接返回
return []
if len(nums) == and sum(nums) == target:
return [nums]
nums.sort() # 先进行排序
res = []
for i in range(len(nums)-): # 第一个下标
if i > and nums[i] == nums[i-]: # 遇到重复的直接跳过
continue
for j in range(i+, len(nums)-): # 第二个下标
if j > i+ and nums[j] == nums[j-]: # 遇到重复直接跳过
continue
start, end = j+, len(nums)-1 # 另外两个下标,指向头和尾部
while start < end:
tem = nums[i] + nums[j] + nums[start] + nums[end]
if tem - target > : # 进行判断,选择相应的移位
end -=
elif tem - target < :
start +=
else: # 找到符合条件的四个数字。
res.append([nums[i], nums[j], nums[start], nums[end]]) # 将其添加进结果集中
while start < end and nums[start] == nums[start+]: # 相同元素直接跳过。
start +=
while start < end and nums[end] == nums[end-]: # 相同元素直接跳过
end -=
start +=
end -=
return res
改进

  上面的算法,在实现之后效率太低,以至于运行结果之超过了百分之10的用户。但是由于自己也想不出什么好的办法,因此取讨论区看了别人的写法,不得不说确实很厉害。下面写上别人给出了一个解决方法,这个方法可以解决N数和的问题。

解决思路以及代码


  这个问题他的解决思路主要是通过分解,将N数和的问题转化为两数和的问题(递归),并且通过传递变量来记录满足结果的条件。

 def fourSum(self, nums, target):
nums.sort()
results = []
self.findNsum(nums, target, , [], results) #因为本题是4数之和的问题,所以传入的参数是4,并且将保存满足条件的数字的变量进行传递
return results def findNsum(self, nums, target, N, result, results):
if len(nums) < N or N < : return # 数组的长度小于N(N数之和)时或者小于2时,直接返回条件。
# solve -sum
if N == : # 当N == 2 时,进行判断, 里面的步骤和三数问题中的步骤一样。
l,r = ,len(nums)-
while l < r:
if nums[l] + nums[r] == target:
results.append(result + [nums[l], nums[r]])
l +=
r -=
while l < r and nums[l] == nums[l - ]:
l +=
while r > l and nums[r] == nums[r + ]:
r -=
elif nums[l] + nums[r] < target:
l +=
else:
r -=
else: # N大于2时进行递归,分解
for i in range(, len(nums)-N+): # careful about range # 第一个指针位置
if target < nums[i]*N or target > nums[-]*N: # 意外情况判定,因为数组是已经排好序的,当第一个元素(最小)乘
break          # 以N时,还比target大,那说明,后面的都不满足,直接返回。后面同理。
if i == or i > and nums[i-] != nums[i]: #recursively reduce N #从第一个看是遍历,并将相应额结果进行传递。
self.findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results)
return

【LeetCode每天一题】4Sum(4数之和)的更多相关文章

  1. LeetCode每天一题之两数之和

    这个LeetCode刷题系列的博客权当是为自己记一下笔记吧.博客系列会从LeetCode的第一题开始刷,同时会从零开始学习[因为我就是零/(ㄒoㄒ)/~~].同时,如果有写错的地方,希望大佬们在评论区 ...

  2. leetcode第15题:三数之和

    给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. ...

  3. Leetcode第1题:两数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的 两个 整数.你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中同样的元素.示例:给定 nums ...

  4. 【LeetCode】18. 4Sum 四数之和

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:four sum, 4sum, 四数之和,题解,leet ...

  5. LeetCode(1): 两数之和

    本内容为LeetCode第一道题目:两数之和 # -*- coding: utf-8 -*- """ Created on Sun Mar 10 19:57:18 201 ...

  6. LeetCode:最接近的三数之和【16】

    LeetCode:最接近的三数之和[16] 题目描述 给定一个包括 n 个整数的数组 nums 和 一个目标值 target.找出 nums 中的三个整数,使得它们的和与 target 最接近.返回这 ...

  7. Leetcode之二分法专题-167. 两数之和 II - 输入有序数组(Two Sum II - Input array is sorted)

    Leetcode之二分法专题-167. 两数之和 II - 输入有序数组(Two Sum II - Input array is sorted) 给定一个已按照升序排列 的有序数组,找到两个数使得它们 ...

  8. LeetCode刷题 - (01)两数之和

    题目描述 给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中同样的元 ...

  9. 【LeetCode刷题】——两数之和.1

    ---恢复内容开始--- 一直想在leetcode上面刷题,但是java刚刚摸了一下门,所以迟迟没有动手,今天做了第一道题,感觉自己实在菜的不行,但是还是学到了很多东西, 就记录一下遇到的问题. 首先 ...

  10. C#LeetCode刷题之#15-三数之和(3Sum)

    目录 问题 示例 分析 问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3618 访问. 给定一个包含 n 个整数的 ...

随机推荐

  1. 3.STM32F4按键扫描函数

    //按键处理函数 //返回按键值 //mode:0,不支持连续按;1,支持连续按; //0,没有任何按键按下 //1, KEY0 按下 2, KEY1 按下 3, KEY2 按下 4, WKUP 按下 ...

  2. day_6.10py面试题:访问百度的过程

    DNS : 解析域名 DHCP:一种协议,自动分配ip 发现局域网中没有ip的电脑分配ip 面试题: 访问百度的整个过程 打开浏览器,访问百度的过程: 1.我的电脑确定有无网关,arp得到默认网管ma ...

  3. Jexus .Net at System.Net.Sockets.Socket.Connect (System.Net.IPAddress[] addresses, System.Int32 port)

    环境:Jexus(独立版)+MVC(5.2.3) +Redis+EF(6.0) Application Exception System.Net.Sockets.SocketException Con ...

  4. 洛谷 P1583魔法照片 & P1051谁拿了最多奖学金 & P1093奖学金

    题目:https://www.luogu.org/problemnew/show/P1583 思路:sort sort sort //#include<bits/stdc++.h> #in ...

  5. CodeForces 1056E - Check Transcription - [字符串hash]

    题目链接:https://codeforces.com/problemset/problem/1056/E One of Arkady's friends works at a huge radio ...

  6. [No0000177]详解/etc/profile、/etc/bash.bahsrc、~/.profile、~/.bashrc的用途

    之前安装Linux的一些软件时,总要修改Linux的配置文件.当时也是一知半解.而且,网上有些安装教程,会说,修改配置文件后要重启Linux.但事实上是不需要重启的. Linux安装时可能要修改的配置 ...

  7. [No000012E]WPF(6/7):概念绑定

    WPF 的体系结构,标记扩展,依赖属性,逻辑树/可视化树,布局,转换等.今天,我们将讨论 WPF 最重要的一部分——绑定.WPF 带来了优秀的数据绑定方式,可以让我们绑定数据对象,这样每次对象发生更改 ...

  8. linux 编程

    edit skill: 1. i:当前光标前插入 2. a:当前光标后插入 3. SHIFT+a—行尾插入 4. SHIFT+i—行首插入 5. o—>下一行插入 6. SHIFT+o--上一行 ...

  9. 生日蛋糕 POJ - 1190 搜索 数学

    http://poj.org/problem?id=1190 题解:四个剪枝. #define _CRT_SECURE_NO_WARNINGS #include<cstring> #inc ...

  10. 【RMAN】RMAN-05001: auxiliary filename conflicts with the target database

    oracle 11.2.0.4 运行以下脚本,使用活动数据库复制技术创建dataguard备库报错rman-005001: run{ duplicate target database for sta ...