您的位置:首页 > 其它

[LeetCode]015-3Sum

2015-12-07 17:04 239 查看
题目:

Given an array S of n integers, are there elements a, b, c 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)


Solution:

思路:

1、先排序,用STL自带Sort函数也行,自己写一个也行。

2、将3个数的sum转化成两个数的sum。很好理解,先确定一个数,再将两个数的和为另一个数的反面。

3、去重,vector有去相邻重复的办法。

4、复杂度为O(n^2)

vector<vector<int>> threeSum(vector<int>& nums)
{
vector<vector<int>> result;
vector<int> temp;

int n = nums.size();
int i,j,k,target,temp_value;

if(n < 3)
return result;
QuickSort(nums,0,n-1);
temp_value = nums[0];
for(i=0;i<n;i++)
{
if(i && temp_value == nums[i])
continue;
target = -nums[i];
j = i+1;
k = n-1;
while(j<k)
{
if(nums[j] + nums[k] == target)
{
temp.push_back(nums[i]);
temp.push_back(nums[j]);
temp.push_back(nums[k]);
result.push_back(temp);
temp.clear();
j++;
k--;
}
else if(nums[j] + nums[k] > target)
k--;
else
j++;
}
temp_value = nums[i];
}
//vector<vector<int>>::iterator it = unique(result.begin(),result.end());
//result.resize(distance(result.begin(),it));

result.erase(unique(result.begin(),result.end()),result.end());
return result;
}

void QuickSort(vector<int>& nums,int low,int high)
{
if(low >= high)
return ;

int first = low;
int last = high;
int pivot = nums[low]; //基准
while(first<last)
{
while(nums[last] >= pivot && last>first)
{
last--;
}
nums[first] = nums[last];
while(nums[first] < pivot && first < last)
{
first++;
}
nums[last] = nums[first];
}
nums[first] = pivot;
QuickSort(nums,low,first-1);
QuickSort(nums,first+1,high);

}


这个博客讲解了kSum,4Sum,3Sum的问题。很全

http://tech-wonderland.net/blog/summary-of-ksum-problems.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode