#include <stdio.h>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
//如果数组长度小于2直接返回空
vector<vector <int>> ans;
int n = nums.size();
if(n <= 2)
return ans;
sort(nums.begin(), nums.end());
for(int i = 0; i < n; ++i){
if(nums[i] > 0)
return ans;
if(nums[i] == nums[i - 1] && i >= 1)
continue; //去重
int left = i + 1;
int right = n - 1;
while(left < right){
//三个数的和小于0
if((nums[i] + nums[left] + nums[right]) < 0)
left++;
//三个数的和大于0
if((nums[i] + nums[left] + nums[right]) > 0)
right--;
if((nums[i] + nums[left] + nums[right]) == 0){
ans.push_back({nums[i], nums[left], nums[right]});
//再进行去重
while((left < right) && nums[left] == nums[left + 1])
left++;
while((left < right) && nums[right] == nums[right - 1])
right--;
left++;
right--;
}
}
}
return ans;
}
};
int main(){
vector<int> t1 = {-1,0,1,2,-1,-4};
//vector<int> t1 = {0,1,1};
Solution a1;
vector<vector<int>> t2 = a1.threeSum(t1);
for(auto x : t2){
cout<<x[0]<<" "<<x[1]<<" "<<x[2]<<endl;
}
return 0;
}
/*
Line 1034: Char 34: runtime error: addition of unsigned offset to 0x603000000070 overflowed to 0x60300000006c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
自己去编译了,可以跑通,但是leecode就是过不去,说啥的都有,数组下标越界到-1了
所以说错了啊!
-4 2 2
-1 -1 2
-1 0 1
*/