3Sum Java

来源:互联网 发布:数据库三种索引含义 编辑:程序博客网 时间:2024/05/05 19:18

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:

  • 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)

Have you been asked this question in an interview?
Check the coding below in detail:
 /*    Better Solution: Time: O(n^2)    Key to solve: HashSet, use 2 additional index inside a loop    Idea: Always sort Array first    iterator array from beginning, use additional two  index start=i+1 and end=length+1    Thus, there are 3 Cases:    1. a==b+c => add into list    2. a>b+c  => start++    3. a<b+c  => end--    */    public List<List<Integer>> threeSum(int[] num) {        List<List<Integer>> triplets =new ArrayList<List<Integer>>();        ArrayList<Integer> sub=new ArrayList<Integer>();        HashSet<ArrayList<Integer>> set=new HashSet<ArrayList<Integer>>();        Arrays.sort(num);        int len=num.length;        for(int i=0;i<len-2;i++){            int start=i+1;            int end=len-1;            int negate=(-num[i]);            while(start<end){                if((num[start]+num[end])==negate){                    sub.add(num[i]);                    sub.add(num[start]);                    sub.add(num[end]);                    if(!set.contains(sub)){                        set.add(sub);                        triplets.add(new ArrayList<Integer>(sub));                    }                    //move the indexs                    start++;                    end--;                    sub.clear();                }                else if(negate>num[start]+num[end]){                    start++;                }else{                    end--;                }            }        }        return triplets;    }



0 0
原创粉丝点击