描述

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. js表单验证处理和childNodes 和children 的区别

    一.对提交表单进行空值验证 html代码: <form action="#"onsubmit="return validate_form(this);" ...

  2. log4j日志输出性能优化-缓存、异步

     转载 1.log4j已成为大型系统必不可少的一部分,log4j可以很方便的帮助我们在程序的任何位置输出所要打印的信息,便于我们对系统在调试阶段和正式运行阶段对问题分析和定位.由于日志级别的不同,对系 ...

  3. The program 'yum' is currently not installed. You can install it by typing:

    执行:(可以直接写成sudo su,就直接转成root了) sudo apt-get updateapt-get install lrzsz 出现:The program 'yum' is curre ...

  4. 微信小程序初探【类微信UI聊天简单实现】

    微信小程序最近很火,火到什么程度,只要你一打开微信,就是它的身影,几乎你用的各个APP都可以在微信中找到它的复制版,另外官方自带的跳一跳更是将它推到了空前至高的位置.对比公众号,就我的感觉来说,有以下 ...

  5. UML 中extend和include的区别

    在UML用例图中有两种关系——包含和扩展,容易混淆,下面通过一张表来区别一下这两种关系.

  6. 关于如何使用SVN的一些建议

    SVN是管理源码的主流方式之一,当多人同时编辑同一项目时经常会出现冲突,本文主要针对Asp.net 项目开发中使用SVN提出一点建议. 1.忽略asp.net 项目中的非源代码文件 .VS目录是vis ...

  7. 解决IAR printf函数输出中文字符乱码问题

    首先看一下IAR的中文字符的坑 这会对调试造成很大的干扰,因为眼见不一定为实. 你所期望的中文打印输出都成了乱码,心在滴血.... 解决方法详细,纯属个人摸索 1.新建notepad++文件,编码方式 ...

  8. Open Live Writer

    最近突然发现我的CSDN博客里面的很多内容都被删除了,虽然我没有用CSDN写博了,不过还是想到可能我现在用的博客园写博,如果有些内容敏感的话会不会也会被删除文章或者关掉我的博客.心里满是担心,于是想说 ...

  9. VS 2017 开发安卓环境搭建 问题总结

    VS 2017可以开发安卓啦,之前一直想尝试开发安卓,但是由于时间忙, Java只学了个基础,不如C#熟练所以一直没有机会接触安卓开发.既然需要利用VS2017开发安卓,那么第一步就是了解VS2017 ...

  10. python为运维人员打造一个监控脚本

    0x00前言: 一直想写一个监控方面的脚本,然后想到了运维这方面的 后来就写了个脚本. 0x001准备: psutil模块 0x02正文: import os import time import r ...