码迷,mamicode.com
首页 > 其他好文 > 详细

15. 3Sum

时间:2016-05-07 13:22:41      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

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.

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.

有一个数组S和n个正数,问是否存在三个元素a,b,c使得a+b+c=0?找到所有唯一的三元组,使他们的的和是0。

注意: 三元组(a,b,c)必须以非降序列的顺序排列。(例如 a≤b≤c)

    结果不能包含重复的序列。

求两个元素的和等于目标值的算法是,先将数组排序,然后使用双指针从两端往中间遍历。将该问题扩展到三个也需要先排序数组,然后使用三个指针,I,J,K,分别指向三个元素。代码结构为两层循环,外层是I,J,K指向I后面的元素,J,K的计算方法类似之前说的两个元素的问题。

需要注意的是结果去重,排完序的数组中,重复的元素总是相邻的,当I指向的元素I-1指向的元素相同,那么这个I就不考虑了,因为包含这个I的三元组必然和包I-1的三元组重复,对于J也是类似处理。

时间复杂度是O(n*n),代码如下:

void AddRet(vector<vector<int>>& ret, int a, int b, int c);

vector<vector<int>> threeSum(vector<int>& nums) {
    vector<vector<int>> ret;
    int n = nums.size();
    sort(nums.begin(), nums.end());
    for (int i=0; i<n-2; ++i)
    {
        if (i!=0 && nums[i] == nums[i-1]) continue;
        int j = i+1;
        int k = n-1;
        while (j < k)
        {
            if (j!=i+1 && nums[j]==nums[j-1]){ ++j; }
            else
            {
                int a = nums[i] + nums[j] + nums[k];
                if (0 == a)
                {
                    AddRet(ret, nums[i], nums[j], nums[k]);
                    ++j; --k;
                }
                else if (a > 0)
                    --k;
                else ++j;
            }
        }
    }
    
    return ret;
}

void AddRet(vector<vector<int>>& ret, int a, int b, int c)
{
    vector<int> tmp;
    tmp.push_back(a);
    tmp.push_back(b);
    tmp.push_back(c);
    ret.push_back(tmp);
}

 

15. 3Sum

标签:

原文地址:http://www.cnblogs.com/zhiguoxu/p/5467829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!