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. drupal drush 在windows下的安装和配置

    一.windows下drupal的安装 参考官网:https://www.drupal.org/node/594744 drush下载:https://github.com/drush-ops/dru ...

  2. JS复制内容到剪贴板(兼容FF/Chrome/Safari所有浏览器)

    现在浏览器种类也越来越多,诸如 IE.Firefox.Chrome.Safari等等,因此现在要实现一个js复制内容到剪贴板的小功能就不是一件那么容易的事了. 在FLASH 9 时代,有一个通杀所有浏 ...

  3. [技术选型] spring boot

    参考博客:http://jinnianshilongnian.iteye.com/blog/1997192 官网:http://projects.spring.io/spring-boot/ 7天学会 ...

  4. [hadoop读书笔记] 第一章 初识 Hadoop

    P3-P4: 目前遇见的问题很简单:硬盘容量不断提升,1TB的已成为主流,然而数据传输速度从1990年的4.4MB/s仅上升到当前约100MB/s 读取一个1TB的硬盘数据需要耗时至少2.5个小时.写 ...

  5. HBase高性能复杂条件查询引擎

    转自:http://blog.csdn.net/bluishglc/article/details/31799255 mark 写在前面 本文2014年7月份发表于InfoQ,HBase的PMC成员T ...

  6. SpannableString属性详解

    1.BackgroundColorSpan 背景色     2.ClickableSpan 文本可点击,有点击事件    3.ForegroundColorSpan 文本颜色(前景色)    4.Ma ...

  7. Network In Network——卷积神经网络的革新

    Network In Network 是13年的一篇paper 引用:Lin M, Chen Q, Yan S. Network in network[J]. arXiv preprint arXiv ...

  8. 第三百八十五节,Django+Xadmin打造上线标准的在线教育平台—登录功能实现,回填数据以及错误提示html

    第三百八十五节,Django+Xadmin打造上线标准的在线教育平台—登录功能实现 1,配置登录路由 from django.conf.urls import url, include # 导入dja ...

  9. Spring JDBC删除数据

    以下示例将展示如何使用Spring jdbc执行删除数据库表中的记录,这里演示如何删除指定student表中的记录. 语法: String deleteQuery = "delete fro ...

  10. Git -- 远程仓库简介

    到目前为止,我们已经掌握了如何在Git仓库里对一个文件进行时光穿梭,你再也不用担心文件备份或者丢失的问题了. 可是有用过集中式版本控制系统SVN的童鞋会站出来说,这些功能在SVN里早就有了,没看出Gi ...