Side Navigation

X

Three Number Sum

Given an array nums of n integers, are there elements a, b, c in nums 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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
class Solution {
    public static void main(String[] args) {
        int[] arr = {-1, 0, 1, 2, -1, -4};
        int target  = 0;
        methodName(arr, target);
    }

    public static List<int[]> methodName(int[] arr, int target){
        List<int[]> list = new ArrayList<>();
        Arrays.sort(arr);
        //-4 -1 -1 0 1 2
        for(int i=0; i<arr.length - 3; i++){
            if(i==0 || arr[i] > arr[i-1]){
                int left = i+1;
                int right = arr.length -1;
                while(left<right){
                    if(arr[i] + arr[left] + arr[right] == target){
                        list.add(new int[] {arr[i], arr[left], arr[right]});
                    }
                    if(arr[i] + arr[left] + arr[right] < target){
                        left++;
                    }else right--;
                }
            }
        }
        System.out.println(Arrays.deepToString(list.toArray()));
        return list;
    }
}

 

You May Also Like

Comments

Leave a Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>