Sunday 6 November 2016

3Sum -Leet Code Java Solutiion

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

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        
        Arrays.sort(nums);
        
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        
        Map<String , Integer> map =  new HashMap<String, Integer>();
        
        HashSet<List<Integer>> set = new HashSet<List<Integer>>();
        
        for(int i = 0 ; i < nums.length -2 ; i++){
            
            int start = i + 1 ;
            int end = nums.length - 1;
            
            while(start < end){
                
                if(nums[i] + nums[start]+ nums[end] == 0){
                    List<Integer> temp = new ArrayList<Integer>();
                    temp.add(nums[i]);
                    temp.add(nums[start]);
                    temp.add(nums[end]);
                    set.add(temp);
                    start++;
                    end--;
                }
                else{
                if(nums[i] + nums[start]+ nums[end] < 0){
                    start++;
                }
                else{
                    end--;
                }
                }
            }
        }
        res.addAll(set);
        return res;
        
    }
}

No comments:

Post a Comment