算法题丨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 ...
随机推荐
- sql语句转为Model
在跟数据库打交道的时候,有一个常用的应用,就是把数据库中的表转为程序中的对象,也就是说表中的列转为对象的属性.对于字段比较少的,我们可以直接复制过去改,但是字段数比较多的时候,借助工具类实现比较方便而 ...
- Gradle下载 Jar 包
使用此方法下载Jar包的前提是已经配置好了Gradle的环境了,配置好的标志是在终端输入gradle不提示command not found. 1. 编写build.gradle文件代码: apply ...
- C# Redis实战(四)
四.写入数据 在C# Redis实战(三)中我们已经配置好了web.config程序,并且能通过C#代码来读取和管理以上配置信息. 接下来,就可以进行Redis的数据写入了.Redis中可以用Stor ...
- js备战春招の四の严格模式
JavaScript 严格模式(strict mode)即在严格的条件下运行. use strict 严格模式下你不能使用未申明的变量 "use strict" 指令只运行出现在脚 ...
- 关于OPC UA Helper 命名空间中的OpcUaClient 类中的订阅函数的更改
原函数是opcUaClient.MonitorValue("ns=4;s=MAIN.d", new Action<double, Action>(MonitorTest ...
- Windows下安装TensorFlow
最近学习TensorFlow,当然前提是装好框架,网上教程很多都是虚拟搭建或者是conda,从我的经验来讲,Windows目前只支持Python3.5版本安装,Python官网上有说明: 本人由于常用 ...
- python 对象和json互相转换
一.python对json的支持 从python2.6开始,python标准库中添加了对json的支持,操作json时,只需要import json即可. 二.python对象转换成json字符串 在 ...
- "码率适配限速”,如何使带宽成本减少30%?
3月28日.29日,B站.爱奇艺即将先后完成IPO.爱奇艺的招股书显示,爱奇艺依然处于亏损状态.2015 年.2016 年.2017 年三年合计亏损约 94 亿元.高昂的版权费是造成视频网站亏损的重要 ...
- thinkphp3.2-更改控制器名后找不到相应的表?报1146的错
用tp在做着自己的小系统的时候,明明在刚才还是能好好地查到表的,在Service用了'D'方法连自己数据库的表,只是更改了自己的控制器名,却报错了... 我就纳闷了,虽然我的控制器和Service用的 ...
- 笔记:Jersey REST 传输格式
通常REST接口会以XML或JSON作为主要传输格式,同时 Jersey 也支持其他的数据格式,比如基本类型.文件.流等格式. 基本类型 Java的基本类型又叫原生类型,包括4种整数(byte.sho ...