15. 3Sum

Given an array S of n integers, are there elements abc 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]
]


此题和那几个two sum类型不同之处在于,三个数的和为0.可以用一个for循环来充当-target,在for循环里面完全当作two sum来做就可以了。关于在for循环里面应该选择什么数据结构,我一开始用了hashmap,在前面的two sum题中,hashmap的value值可以保存索引,又可以保存同样的数组值出现的次数
看了下此题似乎不用存储索引值,如果保存key值出现的次数,感觉是可行的,但是很麻烦。后来考虑用hashset做,发现做出来后有一些测试用例过不去例如上面的例子,[-1,0,1]和[0,1,-1]他们是一样的,然而output上面是两个结果。然后我就想排序,排除掉前后数组元素
相同的情况。但是后来有个测试用例过不去[0,0,0,0].最后决定用两个指针来做了,需要注意的是数组值前后相同的情况,遇到相同情况时候,要移动指针。代码如下:

public class Solution {

    public List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> res = new ArrayList<List<Integer>>();

        Arrays.sort(nums);

        for(int i=0;i<nums.length-2;i++){

            if(i!=0&&nums[i]==nums[i-1]) continue;

            int low = i+1,high = nums.length-1;

            int sum = -nums[i];

            while(low<high){

                if(nums[low]+nums[high]==sum){

                    res.add(Arrays.asList(nums[i],nums[low],nums[high]));

                    while(low<high&&nums[low]==nums[low+1]) low++;

                    while(low<high&&nums[high]==nums[high-1]) high--;

                    low++;

                    high--;

                }else if(nums[low]+nums[high]<sum) low++;

                else high--;

                

            }

        }

        return res;

    }

}




原文地址:https://www.cnblogs.com/codeskiller/p/6353818.html