3Sum
- 首先排序
- 双指针,当我们需要枚举数组中的两个元素时,如果我们发现随着第一个元素的递增,第二个元素是递减的,那么就可以使用双指针的方法
Given an array nums of n integers, are there elements a, b, c in nums 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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
//--------------------------------------------
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
vector<vector<int> > ans;
for (int first = 0; first < n; first++) {
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
int third = n-1;
for (int second = first + 1; second < n; second++) {
if (second > first + 1 && nums[second] == nums[second-1]) {
continue;
}
while(second < third && nums[first] + nums[second] + nums[third] > 0) {
third--;
}
if (second == third) {
break;
}
if (nums[first] + nums[second] + nums[third] == 0) {
ans.push_back({nums[first], nums[second], nums[third]});
}
}
}
return ans;
}
};