###### 15. 3Sum

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n=nums.size();
int i,j,k,length;
int ans;
sort(nums.begin(),nums.end());
unordered_map<int,int> mp;
vector<vector<int>> res;

for(i=0;i<n;i++)
mp[nums[i]]=i;

for(i=0;i<=n-3;i++)
{
if(i>0&&nums[i]==nums[i-1])
continue;
for(j=i+1;j<n;j++)
{
if(j>i+1&&nums[j]==nums[j-1])
continue;
int d=nums[i]+nums[j];
if(d>0)
break;
if(mp.find(-d)!=mp.end())
{
k=mp[-d];
if(k<=j)
break;
vector<int> vt;
vt.push_back(nums[i]);
vt.push_back(nums[j]);
vt.push_back(nums[k]);
res.push_back(vt);
}
}
}
return res;
}
};

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n=nums.size();
int i,j,k;
sort(nums.begin(),nums.end());
vector<vector<int>> res;

for(i=0;i<=n-3;i++)
{
if(i>0&&nums[i]==nums[i-1])
continue;
for(j=i+1,k=n-1;j<k;)
{
if(j>i+1&&nums[j]==nums[j-1])
{
j++;
continue;
}
if(k<n-1&&nums[k]==nums[k+1])
{
k--;
continue;
}
int d=nums[i]+nums[j]+nums[k];
if(d==0)
{
vector<int> vt;
vt.push_back(nums[i]);
vt.push_back(nums[j]);
vt.push_back(nums[k]);
res.push_back(vt);
j++;
k--;
}
else if(d>0)
k--;
else if(d<0)
j++;
}
}
return res;
}
};

#### LeetCode 15 3Sum (C,C++,Java,Python)

2015-05-09 21:06:57

#### LeetCode 15 - 3Sum

2015-05-19 20:03:13

#### leetcode解题之 15. 3Sum Java版（结果为目标值的三个数字）

2017-04-06 18:29:16

#### LeetCode OJ-15.3Sum(三数和问题)

2016-12-28 18:16:19

#### 【Leetcode 15】3Sum 三数和问题 C++

2016-08-14 15:30:05

#### 【LeetCode】3Sum 解题报告

2014-10-30 16:00:34

#### LeetCode 15 — 3Sum（C++ Java Python）

2014-03-20 21:22:02

#### 15. 3Sum hash解法 vs 双指针解法

2017-01-05 00:45:30

#### 15. 3sum Python 实现

2017-08-21 15:43:14

#### Leetcode 15. 3Sum (Medium) (java)

2016-09-22 05:40:35

15. 3Sum