描述

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.

示例

Given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

算法分析

难度:中

分析:要求给定的数组,找出满足条件的3个元素组合,使得3个元素之和等于零。注意,元素不能重复(值可以相同)。

思路:首先,我们需要对数组进行排序,比如数组排序后变为[-4, -1, -1, 0, 1, 2],我们判断第一个元素-4,判断它之后是否有2个元素的和等于4,如果有的话满足条件。因为数组已经排序,只要向当前元素之后查找即可,不用往前查找;

接下来,我们开始遍历排序后的数组,假设当前元素是x,判断本次遍历有解的条件可以转化为找到当前元素之后2个元素和,应该等于0-x,使用夹逼查找方法,检查是否有解,如果有,增加到返回队列,没有的话,进入下一次的遍历,直至找到所有满足条件组合。

代码示例(C#)

public IList<IList<int>> ThreeSum(int[] nums)
{
//排序
Array.Sort(nums);
var res = new List<IList<int>>(); //当前元素向后匹配2个元素,所以最后2个元素不用被遍历
for (int i = 0; i < nums.Length - 2; i++)
{
if (i == 0 || (i > 0 && nums[i] != nums[i - 1]))
{
int lo = i + 1, hi = nums.Length - 1, sum = 0 - nums[i];
while (lo < hi)
{
//找到满足条件元素,添加到返回结果队列
if (nums[lo] + nums[hi] == sum)
{
res.Add(new List<int> { nums[i], nums[lo], nums[hi] });
//防止重复元素
while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
//夹逼查找
lo++; hi--;
}
else if (nums[lo] + nums[hi] < sum) lo++;
else hi--;
}
}
}
return res;
}

复杂度

  • 时间复杂度O (n²).
  • 空间复杂度O (1).

附录

算法题丨3Sum的更多相关文章

  1. 算法题丨3Sum Closest

    描述 Given an array S of n integers, find three integers in S such that the sum is closest to a given ...

  2. 算法题丨4Sum

    描述 Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = ...

  3. 算法题丨Two Sum

    描述 Given an array of integers, return indices of the two numbers such that they add up to a specific ...

  4. 算法题丨Remove Duplicates from Sorted Array II

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? 示例 Giv ...

  5. 算法题丨Longest Consecutive Sequence

    描述 Given an unsorted array of integers, find the length of the longest consecutive elements sequence ...

  6. 算法题丨Remove Element

    描述 Given an array and a value, remove all instances of that value in-place and return the new length ...

  7. 算法题丨Move Zeroes

    描述 Given an array nums, write a function to move all 0's to the end of it while maintaining the rela ...

  8. 算法题丨Next Permutation

    描述 Implement next permutation, which rearranges numbers into the lexicographically next greater perm ...

  9. 算法题丨Remove Duplicates from Sorted Array

    描述 Given a sorted array, remove the duplicates in-place such that each element appear only once and ...

随机推荐

  1. Kafka最佳实践

    一.硬件考量 1.1.内存 不建议为kafka分配超过5g的heap,因为会消耗28-30g的文件系统缓存,而是考虑为kafka的读写预留充足的buffer.Buffer大小的快速计算方法是平均磁盘写 ...

  2. Treesoft数据库管理系统使用说明

    数据列表页面有以下功能:1.直接新添数据行2.直接双击编辑数据3.勾选复制新增数据4.数据按字段排序5.数据列过滤6.结果结果集过滤7.导出数据等 表结构设计页面有以下功能:1.直接新增.删除字段2. ...

  3. Django---视图

    全过程:用户填写相关数据,提交相关请求,链接到对应的视图上,在此视图上(有用户传过来的数据[就是视图要处理的数据],在视图里面对数据进行业务处理,在数据库中crub数据,然后把对应的界面和界面显示需要 ...

  4. ASP.NET Core Web API下事件驱动型架构的实现(四):CQRS架构中聚合与聚合根的实现

    在前面两篇文章中,我详细介绍了基本事件系统的实现,包括事件派发和订阅.通过事件处理器执行上下文来解决对象生命周期问题,以及一个基于RabbitMQ的事件总线的实现.接下来对于事件驱动型架构的讨论,就需 ...

  5. 优化python程序的几点建议

    1.在需要只读序列时,最好使用元组而非列表: 2.使用生成器yield,而不是创建大的元组和列表并在其上进行迭代处理: 3.尽量使用python内置的数据结构,而不实现自己的自定义结构: 4.从小字符 ...

  6. IE 兼容 getElementsByClassName

    getElementsByClassName 通过class获取节点,是很多新人练习原生JS都用到的,项目中也会写,当项目进行到一定程度时,测试IE低版本,忽然发现不支持的时候,瞬间感觉整个人都不好了 ...

  7. java或判断优化小技巧

    写业务代码的时候,我们经常要做条件判断,有的时候条件判断的或判断长达20多个.reg.equals("1") || reg.equals("2") || reg ...

  8. Filecoin2017年Q4进度更新(完整版)

    亲爱的Filecoin支持者.矿工.用户.投资者和广大的社区朋友们, 自从Token销售完成以后,我们便开始集中精力把Filecoin项目从设想变为现实-从实现Filecoin协议的核心代码到打造我们 ...

  9. javascript数组Array强大的splice()方法

    javascript的Array数组提供了强大的splice()方法, 用于对数组元素的增删改 1.删除-用于删除元素,两个参数,第一个参数(要删除第一项的位置),第二个参数(要删除的项数) 删除: ...

  10. jar包和war包的介绍与区别

    在学习maven的过程中接触到了jar包和war包.之前在写小项目的时候真的遇到过war包,当时为了找到jar包,把war包 的后缀名改成了.rar的压缩文件,在里面提取出来jar包来用.其实jar包 ...