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的更多相关文章

  1. [Leetcode][016] 3Sum Closest (Java)

    题目: https://leetcode.com/problems/3sum-closest/ [标签]Array; Two Pointers [个人分析] 这道题和它的姊妹题 3Sum 非常类似, ...

  2. [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 < ...

  3. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

    转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

  4. LeetCode 15 3Sum [sort] <c++>

    LeetCode 15 3Sum [sort] <c++> 给出一个一维数组,找出其中所有和为零的三元组(元素集相同的视作同一个三元组)的集合. C++ 先自己写了一发,虽然过了,但跑了3 ...

  5. LeetCode 16. 3Sum Closest(最接近的三数之和)

    LeetCode 16. 3Sum Closest(最接近的三数之和)

  6. 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 ...

  7. 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 ...

  8. Leetcode Array 15 3sum

      思考的方向不对,即使用了多于别人几倍的时间,也不一定能够达到终点. 我的错误的想法(可以跳过):在leetcode上面做的第四道题,走路一个很大的弯路,收到之前做过的 Container With ...

  9. LeetCode (13): 3Sum Closest

    https://leetcode.com/problems/3sum-closest/ [描述] Given an array S of n integers, find three integers ...

随机推荐

  1. Excel数据批量导入到SqlServer的方法

    1,以Excel为数据源建立连接导入. 关键点在于Excel的数据要有表头,表头要和数据库表的列名一样.连接字符串中HDR=YES不能省略,也就是第一行是表头的意思.IMEX=1;是把数据都当作字符串 ...

  2. Extjs4.x (MVC)Controller中refs以及Ext.ComponentQuery解析

    refs : Object[]5 Array of configs to build up references to views on page. For example: Ext.define(& ...

  3. hbase源码系列(十)HLog与日志恢复

    HLog概述 hbase在写入数据之前会先写入MemStore,成功了再写入HLog,当MemStore的数据丢失的时候,还可以用HLog的数据来进行恢复,下面先看看HLog的图. 旧版的HLog是实 ...

  4. SpringMVC深度探险(四) —— SpringMVC核心配置文件详解

    在上一篇文章中,我们从DispatcherServlet谈起,最终为读者详细分析了SpringMVC的初始化主线的全部过程.整个初始化主线的研究,其实始终围绕着DispatcherServlet.We ...

  5. android下通过app名字打开程序(activity)链接

    Version:0.9 StartHTML:-1 EndHTML:-1 StartFragment:00000099 EndFragment:00004599 1.手机遥控器模拟快捷键启动app 刚开 ...

  6. Generalization and Equilibrium in Generative Adversarial Nets

    Paper link: https://arxiv.org/abs/1703.00573 Blog link: http://www.offconvex.org/2017/03/30/GANs2/ G ...

  7. 实践:C++平台迁移以及如何用C#做C++包装层

    在前面,我们看过OpenTK与MOgre,这二个项目都是C#项目,但是他的实现都是C++.他们简单来说就是一个包装层.常见的包装方式有二种,一种就是我们熟知的显式P/Invoke(DllImport) ...

  8. PDFSharp生成PDF.

    在上面用OpenXML生成word后,原来利用Word2010里的导出成PDF功能就不能用. 然后找开源组件生成PDF,最开始用的是iTextSharp,做完导出报表了才发现,这个开源协议用的是AGP ...

  9. (转)YUV420、YUV422、RGB24转换

    //平面YUV422转平面RGB24static void YUV422p_to_RGB24(unsigned char *yuv422[3], unsigned char *rgb24, int w ...

  10. Linux可视化服务器管理工具webmin

    webmin是一个可视化的linux服务器管理工具,可以帮助我们实现很多功能. Webmin官网: http://www.webmin.com/ 下载地址:http://prdownloads.sou ...