Wednesday, April 9, 2014

Three Sum

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.

Solution:
1. use two pointers , then do 2sum
2. use set 

C++:
  it = unique(vector.begin(), vector.end() )
  vector.resize( distance(vector.begin(), it) )
Code:
vector > threeSum2(vector &num){
 vector > vecResult;

        if(num.size() < 3)
            return vecResult;

        vector vecTriple(3, 0);
        sort(num.begin(), num.end());

        int iCurrentValue = num[0];

        int iCount = num.size() - 2; // (1) trick 1

        for(int i = 0; i < iCount; ++i) {

            if(i && num[i] == iCurrentValue) { // (2) trick 2: trying to avoid repeating triples
                continue;
            }
            // do 2 sum
            vecTriple[0] = num[i];

            int j = i + 1;
            int k = num.size() - 1;
            while(j < k) {
                int iSum = num[j] + num[k];
                if(iSum + vecTriple[0] == 0) {
                    vecTriple[1] = num[j];
                    vecTriple[2] = num[k];
                    vecResult.push_back(vecTriple); // copy constructor
                    ++j;
                    --k;
                }
                else if(iSum + vecTriple[0] < 0)
                    ++j;
                else
                    --k;
            }
            iCurrentValue = num[i];
        }
                // trick 3: indeed remove all repeated triplets
                // trick 4: already sorted, no need to sort the triplets at all, think about why?
        vector< vector >::iterator it = unique(vecResult.begin(), vecResult.end());
        vecResult.resize( distance(vecResult.begin(), it) );
        return vecResult;

}

No comments:

Post a Comment