您的位置:首页 > 编程语言 > C语言/C++

3Sum

2016-07-13 21:24 246 查看
题目描述:

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

解题思路:
首先对数组进行升序排序,然后遍历数组中的元素,固定当前遍历到的元素为第一个数,另外两个数一个从固定的数的后面一个开始,一个从数组的最后一个数开始,移动后两个数找到合适的三元组。

AC代码如下:

class Solution{
public:
vector<vector<int>> threeSum(vector<int>& nums){
vector<vector<int>> ans;
if (nums.size() < 3) return ans;
sort(nums.begin(), nums.end());
int n = nums.size();
for (int i = 0; i < n; ++i){
if (i>0 && nums[i] == nums[i - 1]) continue; //跳过重复的元素,避免结果中出现相同的三元组
int j = i + 1, k = n - 1;
while (j < k){
int sum = nums[i] + nums[j] + nums[k];
if (sum == 0){
vector<int> tmp = { nums[i], nums[j], nums[k] };
ans.push_back(tmp);
while (++j < k && nums[j] == nums[j - 1]); //跳过重复的元素,避免结果中出现相同的三元组
while (j < --k && nums[k] == nums[k + 1]); //跳过重复的元素,避免结果中出现相同的三元组
}
else if(sum>0){
--k;
}
else{//sum<0
++j;
}
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode 3Sum C++