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: 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]
]

解法一:

这一题如果用解决combination的DFS思路,会导致出现很多重复解。比如见下图的例子,假设存在一个解是[-5,-2,7], 由于-2在list中出现了两次,所以这个解至少会出现两次。

1.可以先对nums进行排序。

2. 对于k in range(n), 我们考察[k+1,n]这个区间。由于要求三个数的和为零。所以nums[i]+nums[j]的target就是 -nums[k]。

2.1 如果 nums[i]+nums[j] == target, i 右移一格,j 左移一格。为了不出现重复解,下图的情况 i 要移动到不是-2为止。

2.2 如果 nums[i]+nums[j] < target, i 右移一格

2.3 如果 nums[i]+nums[j] > target, j 左移一格

L12是为了第一个数不出现重复的情况,所以如果nums[k] == nums[k+1], 那么k+1这一步就直接跳过。 另外和two sum不同的是,这里由于事先做了排序,所以并不需要建立一个Hash table。

 class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res = []
n = len(nums)
for k in range(n):
if nums[k] > 0: break
if (k>0 and nums[k] == nums[k-1]): continue
target = 0 - nums[k]
i, j = k+1, n - 1
while i < j:
if nums[i] + nums[j] == target:
res.append([nums[k], nums[i], nums[j]])
while i<j and nums[i] == nums[i+1]:
i += 1
while i<j and nums[j] == nums[j-1]:
j -= 1
i += 1; j -= 1
elif nums[i] + nums[j] < target:
i += 1
else:
j -= 1
return res

Leetcode 15. 3Sum的更多相关文章

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

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

  2. leetcode 15. 3Sum 二维vector

    传送门 15. 3Sum My Submissions Question Total Accepted: 108534 Total Submissions: 584814 Difficulty: Me ...

  3. [LeetCode] 15. 3Sum 三数之和

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  4. LeetCode——15. 3Sum

    一.题目链接:https://leetcode.com/problems/3sum/ 二.题目大意: 3和问题是一个比较经典的问题,它可以看做是由2和问题(见http://www.cnblogs.co ...

  5. LeetCode 15 3Sum(3个数求和为0的组合)

    题目链接 https://leetcode.com/problems/3sum/?tab=Description   Problem: 给定整数集合,找到所有满足a+b+c=0的元素组合,要求该组合不 ...

  6. LeetCode 15. 3Sum(三数之和)

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  7. LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum

    n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...

  8. leetCode 15. 3Sum (3数之和) 解题思路和方法

    3Sum  Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find ...

  9. leetcode 15 3sum & leetcode 18 4sum

    3sum: 1 class Solution { public: vector<vector<int>> threeSum(vector<int>& num ...

随机推荐

  1. entityframework学习笔记--007-实体数据建模基础之继承关系映射TPT

    Table per Type Inheritance (TPT)建模 1.假设你有两张表与一张公共的表密切相关,如图7-1所示,Businiss表与eCommerce表.Retail表有1:0...1 ...

  2. 设计模式之单例模式的简单demo

    /* * 设计模式之单例模式的简单demo */ class Single { /* * 创建一个本类对象. * 和get/set方法思想一样,类不能直接调用对象 * 所以用private限制权限 * ...

  3. 整理分享原生态mac AndroidStudio的快捷键

    使用AndroidStudio开发半年了,一路爬坑至今,刚由Windows转mac一个星期.通过查些资料和自己摸索,记录一些常用的快捷键,犹豫个人不喜欢改快捷键,所以都是原生的.特此分享给大家!欢迎补 ...

  4. ORA-00600: internal error code, arguments: [4194]

    使用PlateSpin复制出来的一数据库服务器(Oracle 10g)在启动数据库实例时遇到"ORA-00600: internal error code, arguments: [4194 ...

  5. python-copy模块使用

    浅拷贝 import copy dic = { "cpu":[80,], "mem":[80,], "disk":[80,] } print ...

  6. DevExpress Carousel 设置水平滑动列表

    DevExpress中Carousel控件的应用 Carousel,直译为旋转木马,即旋转视图,可以做为数据的展示或者菜单项. 要实现触摸左右滑动的效果,其实是比较容易的,直接在CarouselPan ...

  7. WPF Path

    在WPF中,自定义控件,经常用到Path. Path可以绘制多边形.边框.线条.简单的图标等. 1.Xaml中用法: <Path Stroke="DodgerBlue" St ...

  8. 【FLUENT案例】02:DPM模型

    1 引子1.1 案例描述1.2 学习目标1.3 模拟内容2 启动FLUENT并导入网格3 材料设置4 Cell Zones Conditions5 Calculate6 定义Injecions7 定义 ...

  9. Unity性能优化(3)-官方教程Optimizing garbage collection in Unity games翻译

    本文是Unity官方教程,性能优化系列的第三篇<Optimizing garbage collection in Unity games>的翻译. 相关文章: Unity性能优化(1)-官 ...

  10. 《使用Hibernate开发租房系统》内部测试笔试题

    笔试总结 1.在Hibernate中,以下关于主键生成器说法错误的是( C). A.increment可以用于类型为long.short或byte的主键 B.identity用于如SQL Server ...