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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
分析:
先考虑简单的,热身运动:2-sum (参考 《算法》第四版,119页)
考虑问题的简化版,即找出一个输入文件中所有和为0的整数对数量,简单起见,我们还假设所有整数均不相同。要解决这个问题,首先我们先将数组排序(为二分查找做准备)然后对数组中的每个元素进行遍历,使用二分查找,如果找到-a[i]这个元素,那么计数器+1.
其中还包含了3中情况:
* 二分查找失败返回-1,不会增加计数器
* 二分查找返回的j>i, 我们就有a[i] + a[j] = 0;计数器+1
* 二分查找返回的j在0和i之间,我们也有a[i] + a[j] = 0;成立,但是我们不能增加计数器的值,避免重复计数。
这样得到的结果和平方级别的的结果完全相同,同时整个算法的时间与Nlog(N)成正比。
3-sum问题的快速解决方案
和上面一样,我们假设所有整数均各不相同,当且仅当-(a[i] + a[j])在数组中时,整数对(a[i]和a[j])为某个和为0的三元组的一部分。代码将需要进行N*(N - 1)/2次二分查找,每次平局查找时间是与logN成正比,故 总运行时间与N*N*logN成正比。