Thursday, January 1, 2015

Leetcode 15: 3 sum

Problem:
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)
Analysis:
The following solution is to first sort the array and then for each element, we continue to check the larger ones using two pointers and move them accordingly.

Also, as the array could contain duplicated elements, we need to find a way to filter out the same solution.

Code:
public class Solution {
    public List<List<Integer>> threeSum(int[] num) {
        List<List<Integer>> ret=new ArrayList<List<Integer>>();
        if(num==null||num.length<3){
            return ret;
        }
        Arrays.sort(num);
        Set<String> set=new HashSet<String>();
        for(int i=0;i<num.length;i++){
            int j=i+1;
            int k=num.length-1;
            while(j<k){
                if(num[i]+num[j]+num[k]==0){
                    set.add(tsort(num[i],num[j],num[k]));
                    j++;
                    k--;
                }else if(num[i]+num[j]+num[k]>0){
                    k--;
                }else{
                    j++;
                }
            }
        }
        for(String str:set){
            List<Integer> list=new ArrayList<Integer>();
            for(String val:str.split("_")){
                list.add(Integer.parseInt(val));
            }
            ret.add(list);
        }
        return ret;
    }
    private String tsort(int i,int j,int k){
        int min=Math.min(i,Math.min(j,k));
        int max=Math.max(i,Math.max(j,k));
        int mid=(i+j+k)-min-max;
        return min+"_"+mid+"_"+max;
    }
}

No comments:

Post a Comment