LeetCode brush record 7 - find 3 numbers of specified conditions from the array

subject

Given n integers of an array nums, a,b,c are in nums, and a + b + c = 0. Find all three unique numbers in the array, and their sum is zero. (and each group consists of three numbers and each group does not have the same situation)
As follows:

For example, given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Three layer for loop

This may be the simplest way to think of, traversing each group of numbers, then calculating the results, and removing the repetition (this is also the stupid method I think of).

I want to introduce the second solution, which is as follows:

Skip scanned numbers

Because a+b+c=0, we need to fix a number a, reverse (- a), find the number b+c and its equivalent in the remaining numbers, and in case of repetition, we need to continue scanning the next number (the solution comes from leedCode, the link will be at the bottom of the text):

vector<vector<int> > threeSum(vector<int> &num) {
    //[-1, 0, 1, 2, -1, -4]                         

    vector<vector<int> > res;

    std::sort(num.begin(), num.end());

    for (int i = 0; i < num.size(); i++) {

        int target = -num[i];
        int front = i + 1;
        int back = num.size() - 1;

        while (front < back) {

            int sum = num[front] + num[back];

            // Finding answer which start from number num[i]
            if (sum < target)
            {
                front++;
            }
            else if (sum > target)
            {
                back--;
            }
            else 
            {
                vector<int> triplet(3, 0);
                triplet[0] = num[i];
                triplet[1] = num[front];
                triplet[2] = num[back];
                res.push_back(triplet);

                // Processing duplicates of Number 2
                // Rolling the front pointer to the next different number forwards
                while (front < back && num[front] == triplet[1]) front++;

                // Processing duplicates of Number 3
                // Rolling the back pointer to the next different number backwards
                while (front < back && num[back] == triplet[2]) back--;
            }
        }

        // Processing duplicates of Number 1
        while (i + 1 < num.size() && num[i + 1] == num[i])
            i++;
    }
    return res;
}

The original address is here
https://leetcode.com/problems/3sum/discuss/

Posted by cgf2000 on Mon, 11 May 2020 09:50:38 -0700