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

[LeetCode]3Sum

时间:2014-05-16 01:34:36      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   class   code   c   

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)

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num)  {
    std::vector<std::vector<int> > ans;
	if(num.size() < 3) 
	{
		return ans;
	}
	sort(num.begin(), num.end());

	//从左向右扫描,后两个数一个在第一个数后边一个开始,一个从末尾开始
	for(int i = 0; i < num.size() - 2;)
	{
		for(int left = i + 1, right = num.size() - 1; left <right;)
		{
			int tmpsum = num[i] + num[left] + num[right];
			if(tmpsum < 0) 
			{
				left ++;
			}
			else if(tmpsum > 0) 
			{
				right --;
			}
			else
			{
				std::vector<int> tmp;
				tmp.push_back(num[i]);
				tmp.push_back(num[left]);
				tmp.push_back(num[right]);
				ans.push_back(tmp);
				left ++;
				right --;
			}
			while(left != i + 1 && left < right && num[left] == num[left - 1])
			{
				left++;
			}
			while(right != num.size() - 1 && left < right && num[right] == num[right + 1])
			{
				right--;
			}
		}
		i++;
		while(i < num.size() && num[i] == num[i - 1])
		{
			i++;
		}
	}
	return ans;
    }
};


[LeetCode]3Sum,布布扣,bubuko.com

[LeetCode]3Sum

标签:des   style   blog   class   code   c   

原文地址:http://blog.csdn.net/jet_yingjia/article/details/25919631

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