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. Linux排序命令sort详解

    语法格式sort [ -A ] [ -b ] [ -c ] [ -d ] [ -f ] [ -i ] [ -m] [ -n ] [ -r ] [ -u ] [ -o OutFile ][ -t Cha ...

  2. sqoop 常见错误以及处理方式

    Oracle: Connection Reset Errors 错误代码 // :: INFO mapred.JobClient: Task Id : attempt_201105261333_000 ...

  3. mysql国内镜像下载网址

    http://mirrors.sohu.com/mysql/ http://mirrors.ustc.edu.cn/mysql-ftp/Downloads/ 开源镜像站点汇总 http://segme ...

  4. 根据时间获取最新数据 SQL(每一个人或者每一项)

    -- 方法1 select a.* from table1 a from table1 b where b.name=a.name and b.gdtime>a.gdtime) -- 方法2 s ...

  5. background-size 导致的背景不居中问题

    1. 理想中的效果是这样的   2. 然后想改一下圆圈的大小   3. 容器大小为偶数,图片大小为奇数,就会使图片并不真正居中,如果仔细量一下,会发现图片上面比下面多1px! 貌似只有 backgro ...

  6. SpringBoot2 时间类型自动格式化 自动转换

    package com.archibladwitwicke.springboot2.chapter03.configurer; import com.archibladwitwicke.springb ...

  7. Java:集合与数组转换

    List,Set转换为数组的方法. toArray函数有两种形式,一种无参数,一种带参数,注意带参数形式中,要指明数组的大小. public void convertCollectionToArray ...

  8. USB2.0相关应用笔记集锦

    在AN65209中 有一些应用笔记集锦,希望对大家有用.当然AN65209这篇应用笔记很重要,希望大家一定要看!!!一定要看!!!!

  9. JDBC存储过程调用

    在讨论JDBC Statement教程文章时,我们已经学习了如何在JDBC中使用存储过程. 本教程文章与该部分类似,但它将讲解演示有关JDBC SQL转义语法的其他信息. 就像Connection对象 ...

  10. Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.【转】

    今天碰到了一个查询异常问题,上网查了一下,感谢原创和译者 如果你使用的数据库连接类是 the Data Access Application Blocks "SqlHelper" ...