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<vector<int>> threeSum(vector<int> &numbers) {
        // write your code here
        vector<vector<int>> 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<int>{*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;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容