LeetCode - 15. 3Sum

本文介绍了一种寻找数组中三个数相加等于零的有效算法,并提供了详细的实现过程及去重技巧。该算法的时间复杂度为 O(n^2),通过排序和双指针技术高效解决问题。

 15. 3Sum

Problem's Link

 ----------------------------------------------------------------------------

Mean: 

给定一个数列,找出这个数列中和为0的三元组.

analyse:

时间复杂度:O(n^2)

思路很简单,注意一下去重的方法.

Time complexity: O(N)

 

view code

/**
* -----------------------------------------------------------------
* Copyright (c) 2016 crazyacking.All rights reserved.
* -----------------------------------------------------------------
*       Author: crazyacking
*       Date  : 2016-02-16-17.21
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long( LL);
typedef unsigned long long( ULL);
const double eps( 1e-8);

class Solution
{
public :
    vector < vector < int > > threeSum( vector < int >& nums)
    {
        int si = nums . size();
        vector < vector < int > > ret;
        sort( nums . begin (), nums . end());
        int target , sum , low , high;
        for( int i = 0; i < si; i ++)
        {
            target =- nums [ i ];
            low = i + 1;
            high = si - 1;
            // not exist two active integet's sum greater than target
            if( target < 0)
                break;

            while( low < high)
            {
                sum = nums [ low ] + nums [ high ];
                if( sum < target)
                    ++ low;
                else if( sum > target)
                    -- high;
                else
                {
                    vector < int > triple( 3 , 0);
                    triple [ 0 ] = nums [ i ];
                    triple [ 1 ] = nums [ low ];
                    triple [ 2 ] = nums [ high ];
                    ret . push_back( triple);
                    while( low < high && triple [ 1 ] == nums [ low ]) ++ low;
                    while( low < high && triple [ 2 ] == nums [ high ]) -- high;
                }
            }
            while( i + 1 < nums . size() && nums [ i + 1 ] == nums [ i ])
                ++ i;
        }
        return ret;
    }
};

int main()
{
    Solution solution;
    int n;
    while( cin >>n)
    {
        vector < int > ve;
        for( int i = 0; i <n; ++ i)
        {
            int tmp;
            cin >> tmp;
            ve . push_back( tmp);
        }
        vector < vector < int > > ans;
        ans = solution . threeSum( ve);
        for( auto p1: ans)
        {
            for( auto p2: p1)
                cout << p2 << " ";
            cout << endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值