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: 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]
]

问题分析:

1.对于此类问题,我们可以先把数组按升序排序。

2.对该问题转换:由三个数的和变为两个数A,B的和。

3.使用查找算法查找A和B。

4.、查找过程中,要保证三元组的唯一性(不可重复)。

详见代码:

class Solution {
public:
    vector<vector<int> > threeSum(vector<int>& nums) {
    	vector<vector<int> > res;
        sort(nums.begin(), nums.end());//从小到大排序 
        
        for(int i = 0; i < nums.size(); i++)
        {
        	int target = -nums[i];
        	int front = i + 1;
        	int back = nums.size() - 1;
        	
        	while(front < back)
        	{
        		int sum = nums[front] + nums[back];
        		
        		if(sum < target)
        			front++;
        			
        		else if(sum > target)
        			back--;
        			
        		else
        		{
        			vector<int> triplet(3,0);
        			triplet[0] = nums[i];
        			triplet[1] = nums[front];
        			triplet[2] = nums[back];
        			res.push_back(triplet);
        			
        			//保证第二和第三不重复
        			while(front < back && nums[front] == triplet[1]) front++; 
				}
			}
			
			// 保证第一个元素不重复
			while(i + 1 < nums.size() && nums[i + 1] == nums[i]) i++; 
		}
		
		return res;
    }
};
有疑问欢迎交流哈~~