算法题丨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: 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的更多相关文章
- 算法题丨3Sum Closest
描述 Given an array S of n integers, find three integers in S such that the sum is closest to a given ...
- 算法题丨4Sum
描述 Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = ...
- 算法题丨Two Sum
描述 Given an array of integers, return indices of the two numbers such that they add up to a specific ...
- 算法题丨Remove Duplicates from Sorted Array II
描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? 示例 Giv ...
- 算法题丨Longest Consecutive Sequence
描述 Given an unsorted array of integers, find the length of the longest consecutive elements sequence ...
- 算法题丨Remove Element
描述 Given an array and a value, remove all instances of that value in-place and return the new length ...
- 算法题丨Move Zeroes
描述 Given an array nums, write a function to move all 0's to the end of it while maintaining the rela ...
- 算法题丨Next Permutation
描述 Implement next permutation, which rearranges numbers into the lexicographically next greater perm ...
- 算法题丨Remove Duplicates from Sorted Array
描述 Given a sorted array, remove the duplicates in-place such that each element appear only once and ...
随机推荐
- C# Redis实战(二)
二.Redis服务 在C# Redis实战(一)中我将所有文件拷贝到了D盘redis文件夹下,其中redis-server.exe即为其服务端程序,双击即开始运行,如图 可以 ...
- kafka集群参数解析server.properties
#server.properties配置文件 broker.id=1 port=9092 host.name=url1 zookeeper.connect=url1:2181,url2:2181,ur ...
- jqgrid 同列不同行的<select>不相同
如图下所示: 简述原理:设置好表格 所需的字段变量以及字段属性,从后台获取j数据后,在js文件中把数据组合成json格式的字符串,利用字段属性把json数据转换成select,就能实现同列不同行sel ...
- 多线程(三) java中线程的简单使用
java中,启动线程通常是通过Thread或其子类通过调用start()方法启动. 常见使用线程有两种:实现Runnable接口和继承Thread.而继承Thread亦或使用TimerTask其底层依 ...
- NYOJ 题目12喷水装置(二)
#include<iostream> #include<algorithm> #include<cmath> using namespace std; struct ...
- Cloudera Manager及CDH最新版本安装全程记录
大家都知道,Apache Hadoop的配置很繁琐,而且很零散,为此Cloudera公司提供了Clouder Manager工具,而且还封装了Apache Hadoop,flume,spark,hiv ...
- 一场IPFS引领下的共享之风正在走向区块链
中国互联网的高速发展 已经接近10年,小编完整的经历这个过程.这一切我们从一个小网站 饭否 说起... 互联网 2006年3月16:Twitter上线 2007年5月12: 饭否上线 饭否是中国第一 ...
- HashMap源码解析(JDK1.8)
package java.util; import sun.misc.SharedSecrets; import java.io.IOException; import java.io.Invalid ...
- json字符串对象内嵌json对象
有时候需要在json的key:value字符串对象中再嵌入一个json对象,如果需要把如下的json对象作为字符串嵌入到json字符串对象中: { "type": 2, " ...
- Java I/O 总结
Java I/O的的架构使用了装饰器的模式,我们在使用流的时候需要新建很多的装饰器对象,对源数据进行层层包装.各个包装类名以及它们的应用场景比较多,初学的时候难以摸清规律,这里我把它们归一下类,方便大 ...