标签:leetcode
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)
? Thesolutionsetmustnotcontainduplicatetriplets.
For example, given array S = {-1 0 1 2 -1 -4}.
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
先对数组进行非递减排序, 确定一个数i,在对其后面的序列使用 左右游标p,q夹逼(PS:这个词确实有点)。
对num[i],num[p],num[q]三者的和sum 进行判断。
如果 sum>target: q--; 去重;
如果 sum<target: p++; 去重;
如果 sum==target: 返回结果; 去重;
这个算法的时间复杂度为O(n^2).
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > result;
if(num.size()<3) return result;
sort(num.begin(),num.end());
printf("size: %d\n", num.size());
for (int i=0; i<num.size(); ++i){
if(i!=0 && num[i]==num[i-1]) continue;
int p = i+1, q = num.size()-1;
int sum = 0;
while(p < q){
sum = num[i]+num[p]+num[q];
if(sum<0){
++p;
while(num[p]==num[p-1] &&p<q) ++p;
}else if(sum>0){
--q;
while(num[q]==num[q+1] &&p<q) --q;
}else{
printf("%d, %d, %d",num[i], num[p], num[q]);
//result.push_back({num[i], num[p], num[q]});
vector<int> newRes;
newRes.push_back(num[i]);
newRes.push_back(num[p]);
newRes.push_back(num[q]);
result.push_back(newRes);
while(++p<q && num[p]==num[p-1]){
//do nothing
}
while(--q>p && num[q]==num[q+1]){
//do nothing
}
}
}
}
return result;
}
};
int main(int argc, char *argv[]) {
int a[] = {-1,0,1};
vector<int> v(&a[0],&a[3]);
Solution s;
vector<vector<int> > result = s.threeSum(v);
}
再补充其相关题,思路是一样的,直接上代码:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int result;
int min_gap = INT_MAX;
sort(nums.begin(), nums.end());
for(int i=0; i<nums.size(); ++i){
int p = i+1;
int q = nums.size()-1;
while(p < q){
int sum = nums[i] + nums[p] + nums[q];
int gap = abs(sum-target);
if(gap < min_gap){
result = sum;
min_gap = gap;
}
if(sum < target){
++p;
}else{
--q;
}
}
}
return result;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:leetcode
原文地址:http://blog.csdn.net/mennoa/article/details/46863791