Description
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]
]
AC代码
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
if(nums.empty()) {
return result;
}
size_t n_size = nums.size();
sort(nums.begin(), nums.end());
for(int i=0; i<n_size; ++i) {
//如果当前值大于0的话,就没有继续下去的意义了
if(nums[i] > 0) {
break;
}
if(i > 0 && nums[i] == nums[i-1]) {
continue;
}
int left = i + 1;
int right = n_size -1;
while(left < right) {
int sum = nums[i] + nums[left] + nums[right];
if(sum > 0) {
right--;
} else if (sum < 0) {
left++;
} else { //sum=0,存储结果
result.push_back({nums[i], nums[left], nums[right]});
int last_left = left;
int last_right = right;
while(left < right && nums[left] == nums[last_left]) {
left++;
}
while(left < right && nums[right] == nums[last_right]) {
right--;
}
}
}
}
return result;
}
};
测试代码
int main() {
Solution s;
vector<int> a1{-1, 0, 1, 2, -1, -4};
vector<vector<int>> result1 = s.threeSum(a1);
for(vector<int> combo:result1) {
for(int i=0; i<combo.size(); i++) {
cout << combo[i] << " ";
}
cout << endl;
}
vector<int> a2{0, 0, 0};
vector<vector<int>> result2 = s.threeSum(a2);
for(vector<int> combo:result2) {
for(int i=0; i<combo.size(); i++) {
cout << combo[i] << " ";
}
cout << endl;
}
}
总结
这一题其实比较难了,核心思路就是先对给定的数组进行排序,然后设定一个指针进行遍历,把负数部分遍历一遍,然后设定前后各一个指针,计算三者的和,根据和的正负性决定指针的移动方向。题目中比较容易忽视的情况就是如果数组里有数值相等,这里需要多加一些判定条件,如果遇到了连续的相等数值,需要跳过。