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.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
日常刷题训练,保持思维的敏捷性。感觉这类题已经有了深深地套路在里面!
题目目标:在一维数组中,寻找三个数之和为0的组合,此类组合可能会有多个。不重复的输出三个数的组合。
题目分析:这次就不献上自己的思路了,直接用大神的最优解吧,以下是结合自己对题目的看法和事后解析写的一点分享。
题目解法:
(1)观察例子给出的解,每组解中的数字都是升序且无重复数据,所以输出时必须注意。而且怀疑在搜索时是不是数组已经是升序排列。
(2)第一步将所给的数组排序为自然升序。
(3)开始搜索:先确定每组输出元素的第一个nums[i],也就是最小的一个。如果在该元素左侧开始进行搜索来匹配三元组的话,假设可以匹配到a形成三元组(a,nums[i],x),那么在i指向a时,也会形成三元组(a,nums[i],x)。所以下面将在nums[i]的右侧进行搜索。
(4)使用常见的双端搜索法,进行搜索(可以参考LeetCode中Container With Most Water和我的相关博文),来达到O(n)的时间复杂度。
(5)搜索内循环的解释详细见注释
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> space=new LinkedList<>();
Arrays.sort(nums);//将数组排序
int i=0;
for(i=0;i<nums.length;i++){
if(i==0 || (i>0 && nums[i]!=nums[i-1])){
//当i=0时直接开始搜索,i>0时则要检查i指向的左侧相邻元素是否与其相等,若相等,因为相当于已经搜索过了,则此轮搜索跳过
int lower=i+1,high=nums.length-1,tofit=0-nums[i];
//将搜索低位置为i+1,高位为length-1
while(lower<high){
if(tofit==nums[lower]+nums[high]){
space.add(Arrays.asList(nums[i],nums[lower],nums[high]));
//如果搜索的结果满足了和为零,则将其加入list(Arrays.asList超级好用有木有,我竟然知道的这么晚)
while(nums[high-1]==nums[high]&&lower<high)high--;//若发现搜到的高位元素的左侧有相等的,则继续修改高位index,避免搜出重复解
while(nums[lower+1]==nums[lower]&&lower<high)lower++;
high--;//进入新的位置
lower++;
}else if(tofit > nums[lower]+nums[high])lower++;
//这里这么个写法是有学问的,如果发现tofit较大,那么nums[lower]+nums[high]要往大了走:(1)high++,这样很有可能搜出重复解(2)lower++,很安全啊
else high--;
//与上面类似
}
}
}
return space;
}
}