LeetCode OJ 之 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.

给定含有n个整数的数列,求数列中的三个数a,b,c使得a + b + c = 0,找出不重复的数。

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)

思路:

先对数组排序,然后第一个数先固定,后两个数一个在最前,一个在最后,进行遍历。然后第一个数后移,再进行遍历。

代码:

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) 
    {
        int digit=0;//三个数的和
    	vector<vector<int>> result;
    	int len = num.size();
    	if (len < 3) 
    		return result;
    	sort(num.begin(), num.end());
    	for(int i = 0 ; i < len ; i++)
    	{
    	    //由于题目要求不能有重复的,因此如果当前的数和上次的相同,则忽略
            if(i > 0 && num[i]==num[i-1])  
                    continue;  
    		int j = i + 1;
    		int k = len - 1;
    		while(j < k)
    		{
    		    //同上
    			if(k < len -1 && num[k] == num[k+1])
    			{
    				k--;
    				continue;
    			}
    			//如果当前三个数和较小,则j向后移动,使得总数增大
    			if(num[j] + num[k] + num[i] < digit)
    			{
    				j++;
    			}
    			else
    			{
    				if(num[j] + num[k] + num[i] > digit)
    				{
    					k--;
    				}
    				else
    				{
    					vector<int> cur;//在这里面定义可以把上次循环的cur覆盖掉
    					cur.push_back(num[i]);
    					cur.push_back(num[j]);
    					cur.push_back(num[k]);
    					result.push_back(cur);
    					j++;
    					k--;
    				}
    
    			}
    		}
    	}
    	return result;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值