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.

Example:
Given array = {-1 0 1 2 -1 -4},
Solution set is:
    (-1, 0, 1)

    (-1, -1, 2)

JavaScript Code

function threeSum(num) {
        //sort array
        num.sort();
 
        var result = [];
        var each = [];
        for(var i=0; i<num.length; i++){
            if(num[i] > 0) break;
 
            for(var j=i+1; j<num.length; j++){
                if(num[i] + num[j] > 0 && num[j] > 0) break;
 
                for(var k=j+1; k<num.length; k++){
                  if(num[i] + num[j] + num[k] == 0) {
 
                      each.push(num[i]);
                      each.push(num[j]);
                      each.push(num[k]);
                      result.push(each);
                      each = [];
                  }
                }
            }
        }
 
       return result;
}

console.log(threeSum([-1,0,1,2,-1,-4]));

0 comments:

Blogroll

Follow this blog by Email

Popular Posts