LeetCode[Array]----3Sum
3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c =
0?
Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
分析:
该题是LeetCode-Two Sum一题的升级版。
题目的要求是,给定一个数组,要求找到一组不重合的解(a,b,c),使得a + b + c等于0.
借鉴Two Sum题的(编程之美上的)思路,我们能够将当中的一个数a作为target,然后问题就转化为了求b + c等于-a的Two Sum问题。
详细解说一下:我们首先还是对数组nums进行排序。这样后面查找时就行使用双指针分别从前和从后向中间開始遍历了。
在排序后nums中依次从左边開始选择一个元素乘以-1作为target,然后使用左右两个指针分别从前和往后開始遍历,假设两指针的相应的元素和等于target。则将这三个元素存储作为一个解,然后左右指针分别向中间移动;假设两指针的相应元素和大于target,那么右指针向左移动。假设两指针的相应元素和小于target,那么左指针向右移动。
代码:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
if len(nums) < 3:
return []
# 对数组进行排序。方便后面的查找
nums.sort()
for i in range(len(nums) - 2):
# 把a作为target
target = nums[i] * -1
# 问题转化为b+c == -a的情况了
a = i + 1
b = len(nums) - 1
while a < b:
if nums[a] + nums[b] == target:
res.append([nums[i], nums[a], nums[b]])
a += 1
b -= 1
elif nums[a] + nums[b] > target:
b -= 1
else:
a += 1
dummyres = []
# 因为上面的方法产生的解有反复,须要去重
for i in range(len(res)):
if res[i] in dummyres:
pass
else:
dummyres.append(res[i])
return dummyres
改进一下:
上面的代码产生的解中有反复,假设我们可以在求解的过程中过滤掉左/右指针移动后的元素值不发生变化这两种情况。就可以避免在求解过程中产生反复解。
改进的代码:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
if len(nums) < 3:
return []
nums.sort()
for i in range(len(nums) - 2):
# 当nums[i]大于0时。后面的元素和一定大于0,不须要再进行推断了
# 当nums[i]与前一个元素值同样时,解是同样的
if nums[i] > 0 or i and nums[i] == nums[i-1]:
continue
target = -nums[i]
left = i + 1
right = len(nums) - 1
while left < right:
# 当nums[right]小于0时。a,b,c三个元素值都小于0。也不须要进行-a == b+c的推断了
if nums[right] < 0:
break
if nums[left] + nums[right] == target:
res.append([nums[i], nums[left], nums[right]])
while left < right and nums[left+1] == nums[left]: # 当nums[left]值与下一个元素值同样时,解同样
left += 1
while left < right and nums[right-1] == nums[right]:
right -= 1
left += 1
right -= 1
elif nums[left] + nums[right] > target:
right -= 1
else:
left += 1
return res
LeetCode[Array]----3Sum的更多相关文章
- [Leetcode][016] 3Sum Closest (Java)
题目: https://leetcode.com/problems/3sum-closest/ [标签]Array; Two Pointers [个人分析] 这道题和它的姊妹题 3Sum 非常类似, ...
- [LeetCode] 259. 3Sum Smaller 三数之和较小值
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 < ...
- 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)
转自 http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...
- LeetCode 15 3Sum [sort] <c++>
LeetCode 15 3Sum [sort] <c++> 给出一个一维数组,找出其中所有和为零的三元组(元素集相同的视作同一个三元组)的集合. C++ 先自己写了一发,虽然过了,但跑了3 ...
- LeetCode 16. 3Sum Closest(最接近的三数之和)
LeetCode 16. 3Sum Closest(最接近的三数之和)
- Leetcode Array 16 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...
- Array + two points leetcode.16 - 3Sum Closest
题面 Given an array nums of n integers and an integer target, find three integers in nums such that th ...
- Leetcode Array 15 3sum
思考的方向不对,即使用了多于别人几倍的时间,也不一定能够达到终点. 我的错误的想法(可以跳过):在leetcode上面做的第四道题,走路一个很大的弯路,收到之前做过的 Container With ...
- LeetCode (13): 3Sum Closest
https://leetcode.com/problems/3sum-closest/ [描述] Given an array S of n integers, find three integers ...
随机推荐
- 十大要避免的Ext JS开发方法
原文地址:http://www.sencha.com/blog/top-10-ext-js-development-practices-to-avoid/ 作者:Sean LanktreeSean i ...
- PCL深度图像(1)
目前深度图像的获取方法有激光雷达深度成像法,计算机立体视觉成像,坐标测量机法,莫尔条纹法,结构光法等等,针对深度图像的研究重点主要集中在以下几个方面,深度图像的分割技术 ,深度图像的边缘检测技术 ,基 ...
- 制作nodejs项目镜像,实现docker下的快速部署
前言 前面的文章<centos7+ docker1.12 实践部署docker及配置direct_lvm>中,已经实践了如何在centos7下安装,配置docker, 所以接下来就打算去制 ...
- R语言-向量化操作(apply、tapply、lapply、sapply、mapply、table等)
一.apply函数(对一个数组按行或者按列进行计算): 使用格式为:apply(X, MARGIN, FUN, ...) 其中X为一个数组:MARGIN为一个向量(表示要将函数FUN应用到X的行还是列 ...
- jquery-仿flash的一个导航栏特效
演示地址:http://itxiaoming.sinaapp.com/demo05/demo.html <html> <head> <meta http-equiv=&q ...
- XmlnsDefinition for a Cool Namespace Mapping
In XAML, when you want to reference a CLR type, you have to add a namespace mapping that maps the XM ...
- List<Map<String, Object>>是什么意思
List集合中的对象是一个Map对象,而这个Map对象的键是String类型,值是Object类型 List以Map接口对象为列表对象. Map以String为键,以Object为值. List里只能 ...
- IDEA中 @override报错的解决方法
今天用IDEA导入一个java工程时,碰上一个问题,代码中所有@override处标红,并提示:@override不支持对接口的实现. 网上百度了一下发现, 原因是引用JDK5版本中存在小bug的问题 ...
- SAP,Oracle和国产系统的比较心得
以下这个心得感同身受,小生如今好歹也做过十几家企业,包括民企,中大型外企,国企的项目, 都经历了TMD的从金蝶用友切换到Oracle, SAP 每当上线的时候 总有用户跳出来比较说 SAP,Ora ...
- 【转载】Exchange 2010配置与安装实用手册
Exchange 2010配置与安装实用手册 在Exchange 2010配置的时候主要分三大部分,这分别是网络配置.准备存储以及相关的安装策略和过程.同时还需要注意和其他的Windows软件相协调. ...