3Sum
题目描述:
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] ]
题目大意:
给定一个数组,找出三个数,这三个数的和等于0;
首先我们将数列进行排序。我们可以固定地一个数字,然后从用两个指针,一个从前面往后,一个从后面往前。
大体思路就是这样。在具体操作过程中需要考虑重复元素的操作,在固定第一个数的时候,如果当前数字等于之前的数字,那就直接跳过不进行操作。同理,两个指针移动的时候遇到相同元素也要跳过。
题目代码:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<int> tem(3);
vector<vector<int>>ans;
int begin, end;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); i++){
if(nums[i] > 0) break;
if(i && nums[i] == nums[i-1]) continue;
begin = i+1;
end = nums.size()-1;
while(begin < end){
if(nums[i]+nums[begin]+nums[end] == 0){
ans.push_back({nums[i],nums[begin],nums[end]});
while(begin < end && nums[begin] == nums[begin+1]) begin++;
while(begin < end && nums[end] == nums[end-1]) end--;
begin++; end--;
}else if(nums[i]+nums[begin]+nums[end] > 0){
end--;
}else{
begin++;
}
}
}
return ans;
}
};