LintCode 57. 3Sum

原题

LintCode 57. 3Sum

Description

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.

Notice

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

For example, given array S = {-1 0 1 2 -1 -4}, A solution set is:
(-1, 0, 1)
(-1, -1, 2

解题

题意是,从一组中,找到三个数,要求这三个数加起来为0,找到所有这样的组合。

最朴素的思想是直接进行三重循环,时间复杂度为O(n^3)。

有一个较为简单的问题是2Sum,即从一组数中找到两个数,使得两个数加起来为0。这道题中,我们可以先固定一个数,那么这个问题就退化为2Sum。具体做法为:
首先将数组排序,然后从遍历数组中的每一位数,将此数作为三个数中的第一个数,然后再这个数的右边寻找两个数,使得这三个数和为0。这两个数的寻找过程可以参考2Sum,即使用两个指针分别指向数组的首尾,然后向中间靠近。

代码

class Solution {
public:
    /*
    * @param numbers: Give an array numbers of n integer
    * @return: Find all unique triplets in the array which gives the sum of zero.
    */
    vector> threeSum(vector &numbers) {
        // write your code here
        vector> ans;
        sort(numbers.begin(), numbers.end());
        auto it = numbers.begin();
        while (it != numbers.end()) {
            if (*it > 0) break;
            if (it != numbers.begin() && *it == *(it - 1)) {
                it++; continue;
            }
            auto nega = it + 1;
            auto posi = numbers.end() - 1;
            while (nega < posi) {
                int sum = *nega + *posi + *it;
                if (sum == 0) {
                    ans.push_back(vector{*it, *nega, *posi});
                    posi--;
                    while (*posi == *(posi + 1)) posi--;
                    nega++;
                    while (*nega == *(nega - 1)) nega++;
                } else if (sum > 0) {
                    posi--;
                } else {
                    nega++;
                }
            }
            it++;
        }
        return ans;
    }
};

你可能感兴趣的:(LintCode 57. 3Sum)