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

[leetcode]3Sum

时间:2014-11-15 23:19:27      阅读:347      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, abc)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)

基本思路:

此题最naiev的做法是3层循环遍历所有可能的情况。此时时间复杂度是O(n^3);

较好的做法是对num数组排序。然后外层设置1层循环,内层即可看作求两个数的和为给定值的问题。(注意:此时的数组是有序的呦!较好的用好这个序关系就可以在O(n)的时间内解决2Sum问题。)。该方法最终的时间复杂度是O(n^2).


代码:

vector<vector<int> > threeSum(vector<int> &num) { //C++
    vector<vector<int> > res;
    if (num.size() <= 2) return res;
    sort(num.begin(), num.end());
    int twoSum;
    for (int i = 0; i < num.size() - 2;)
    {
        int l = i + 1, r = num.size() - 1;
        twoSum = 0 - num[i];
        while (l < r)
        {
            if (num[l] + num[r] < twoSum) l++;
            else if (num[l] + num[r] == twoSum)
            {
                vector<int> three(3);
                three[0] = num[i];
                three[1] = num[l];
                three[2] = num[r];
                res.push_back(three);
                do { l++; }while (l < r && num[l - 1] == num[l]);
                do { r--; }while (l < r && num[r + 1] == num[r]);
            }
            else r--;
        }
        do{ i++; }while (i < num.size() - 1 && num[i - 1] == num[i]);
    }
    sort(res.begin(),res.end());
    return res;
}


[leetcode]3Sum

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/41151955

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