【LeetCode】15. 3Sum


3Sum

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.

 

    For example, given array S = {-1 0 1 2 -1 -4},

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

先升序排序,然后用第一重for循环确定第一个数字。

然后在第二重循环里,第二、第三个数字分别从两端往中间扫。

如果三个数的sum等于0,得到一组解。

如果三个数的sum小于0,说明需要增大,所以第二个数往右移。

如果三个数的sum大于0,说明需要减小,所以第三个数往左移。

时间复杂度:O(n2)

注意:

1、排序之后天然满足non-descending order的要求

2、为了避免重复,在没有空间要求情况下可以用map,但是也可以跳过重复元素来做。

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        vector<vector<int> > ret;
        int size = num.size();
        sort(num.begin(), num.end());
        for(int i = 0; i < size; i ++)
        {
            //skip same i
            while(i > 0 && i < size && num[i] == num[i-1])
                i ++;
            int j = i + 1;
            int k = size - 1;
            while(j < k)
            {
                int sum = num[i] + num[j] + num[k];
                if(sum == 0)
                {
                    vector<int> cur(3);
                    cur[0] = num[i];
                    cur[1] = num[j];
                    cur[2] = num[k];
                    ret.push_back(cur);
                    j ++;
                    k --;
                    //skip same j
                    while(j < k && num[j] == num[j-1])
                        j ++;
                    //skip same k
                    while(k > j && num[k] == num[k+1])
                        k --;
                }
                else if(sum < 0)
                {
                    j ++;
                    //skip same j
                    while(j < k && num[j] == num[j-1])
                        j ++;
                }
                else
                {
                    k --;
                    //skip same k
                    while(k > j && num[k] == num[k+1])
                        k --;
                }
            }
        }
        return ret;
    }
};


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2024 CODEPRJ.COM