算法题丨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 ...
随机推荐
- JS中的闭包问题
一.闭包:在函数外也可使用局部变量的特殊语法现象 全局变量 VS 局部变量: 全局变量:优点:可共享,可重用; 缺点:在任意位置都可随意修改——全局污染 局部变量:优点:安全 缺点:不可共享,不可重用 ...
- Java仪器数据文件解析-PDF文件
一.概述 使用pdfbox可生成Pdf文件,同样可以解析PDF文本内容. pdfbox链接:https://pdfbox.apache.org/ 二.PDF文本内容解析 File file = new ...
- jsp常见jstl语法(二)
<c:choose>标签与Javascript switch语句的功能一样,用于在众多选项中做出选择. 语法格式 <c:choose> <c:when test=&quo ...
- Y2 MyBatis(二)
春节后的第一次课 1.整合日志(log4j和logback) (1)log4j和logback都是一个日志记录框架 (2)appender记住两个 stdout控制台显示日志,file记录文件中 (3 ...
- jqgrid 同列不同行的<select>不相同
如图下所示: 简述原理:设置好表格 所需的字段变量以及字段属性,从后台获取j数据后,在js文件中把数据组合成json格式的字符串,利用字段属性把json数据转换成select,就能实现同列不同行sel ...
- QBlog V2.5 源码开放下载(ASP.NET 番外系列之开端)
QBlog简介: QBlog:是一个套博客系统,开源.支持多用户.多语言.及方便的多数据库切换. QBlog下载:http://www.cyqdata.com/download/article-det ...
- IM-iOS退出后台接受消息,app退出后台能接收到推送
App被失活状态的时候可以走苹果的APNS:但是在活跃的时候却接受不到推送! 那就用到本地推送:UILocalNotification 消息神器. 处理不好可能会有很多本地推送到来,那么问题来了要在什 ...
- 从Socket入门到BIO,NIO,multiplexing,AIO
Socket入门 最简单的Server端读取Client端内容的demo public class Server { public static void main(String [] args) t ...
- Java面试宝典-2017
Java面试宝典2017版 一. Java基础部分........................................................................... ...
- push_back和emplace_back的区别
emplace_back能就地通过参数构造对象,不需要拷贝或者移动内存,相比push_back能更好地避免内存的拷贝与移动,使容器插入元素的性能得到进一步提升.在大多数情况下应该优先使用emplace ...