[LeetCode]3Sum

来源:互联网 发布:网络求职招聘 编辑:程序博客网 时间:2024/06/05 23:07

Question:
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]
]


本题难度medium。由于有了做Container With Most Water 的经验,本题一看就知道首先要排序,其次要用夹逼方法,但是在夹逼方法的具体细节上出了问题:
我仍然使用从两边夹逼的办法:

when sum<0,left point shifts  to rightwhen sum>=0,right point shifts to left

问题就出现在sum=0上,这样会导致出现漏解。正确的办法是固定一个元素,然后在剩下范围内使用夹逼,这种方法就是不断缩小解空间,因此不会漏解。另外要注意避免重复解,办法就是循环中跳过它。

【参考】
[LeetCode]3Sum

【经验教训】
一旦你用了循环,无论在哪里使用,始终不要忘记对边界进行检查。

代码如下:

public class Solution {    public List<List<Integer>> threeSum(int[] nums) {        //require        List<List<Integer>> ans=new ArrayList<List<Integer>>();        int size=nums.length;        if(size<3)            return ans;        //sort        Arrays.sort(nums);        if(nums[0]>0||nums[size-1]<0)            return ans;        //invariant        for(int i=0;i<size-2&&nums[i]<=0;i++){            //kick off the same element            if (i != 0 && nums[i] == nums[i-1])                  continue;              int l=i+1,r=size-1;            do{                int sum=nums[i]+nums[l]+nums[r];                if(sum>0){                    do{                        r--;                    }while(r>l&&nums[r]==nums[r+1]);                }else if(sum<0){                    do{                        l++;                    }while(r>l&&nums[l-1]==nums[l]);                }                else{                        List<Integer> list= Arrays.asList(nums[i],nums[l],nums[r]);                        ans.add(list);                        do{                            r--;                        }while(r>l&&nums[r]==nums[r+1]);                        do{                            l++;                        }while(r>l&&nums[l-1]==nums[l]);                }            }while(l<r);        }        //ensure        return ans;    }}
0 0
原创粉丝点击