15. 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] ]
Subscribe to see which companies asked this question
虽然比较简单,但提交几次都有几个案例没有通过。
注意几点。
1.为避免重复加上判断if (i == 0 || nums[i] != nums[i - 1])
2.一个循环里也可能有多个解,因此不能break,而且为避免重复:
pa++; pb--;
while (pa<pb&&nums[pa - 1] == nums[pa]) pa++;
while (pa<pb&&nums[pb + 1] == nums[pb]) pb--;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
for (int i = 0; i < nums.size(); i++){
if (i == 0 || nums[i] != nums[i - 1]){///
int sum = -nums[i];
int pa = i + 1, pb = nums.size() - 1;
while (pa < pb){
if (nums[pa] + nums[pb] == sum){
vector<int> item;
item.push_back(nums[i]);
item.push_back(nums[pa]);
item.push_back(nums[pb]);
res.push_back(item);
//break;
pa++; pb--;
while (pa<pb&&nums[pa - 1] == nums[pa]) pa++;
while (pa<pb&&nums[pb + 1] == nums[pb]) pb--;
}
else if (nums[pa] + nums[pb]>sum){
pb--;
}
else{
pa++;
}
}
}
}
return res;
}
};