LeetCode——3Sum
1. Question
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]
]
2. Solution
-
先排序,然后对于每一个nums[i],在其后找到两个数字num[j]和num[k],j<k,使得三者和为0。
-
去掉重复的组合,如果满足三者为0,那么j需要后移到一个不同的数,k也需要前移到一个不同的数。
-
重复的nums[i]也需要去掉,因为nums[i]和nums[i+1] 都是和其后的进行组合,如果两个一样的话,就重复了,需要去掉。
3. Code
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
if (nums.size() <= 2)
return vector<vector<int>>();
sort(nums.begin(), nums.end());
vector<vector<int>> res;
for (int i = 0; i < nums.size() - 2; i++) {
int start = i + 1;
int end = nums.size() - 1;
while (start < end) {
int tmp = nums[start] + nums[end];
int target = -nums[i];
if (tmp == target) {
vector<int> ele;
ele.push_back(nums[i]);
ele.push_back(nums[start]);
ele.push_back(nums[end]);
res.push_back(ele);
// 去掉start重复的
while (start < end && nums[start] == ele[1])
start++;
// 去掉end重复的
while (end > start && nums[end] == ele[2])
end--;
} else if (tmp > target)
end--;
else
start++;
}
// 去掉nums[i]重复的
while (i + 1 < nums.size() - 2 && nums[i + 1] == nums[i])
i++;
}
return res;
}
};