class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
int len=nums.size();
sort(nums.begin(),nums.end());
vector<int> tmp(3);
for(int i=0;i<len;i++){
if(nums[i]>0) break;
if(i>0&&nums[i]==nums[i-1]) continue;
int start=i+1,end=len-1;
while(start<end){
int sum=nums[i]+nums[start]+nums[end];
if(sum==0){
tmp[0]=nums[i];
tmp[1]=nums[start];
tmp[2]=nums[end];
start++;
end--;
res.push_back(tmp);
while(start<end&&nums[start]==nums[start-1]) start++;
while(start<end&&nums[end]==nums[end+1]) end--;
}else if(sum>0)
end--;
else start++;
}
}
return res;
}
};
LeetCode 15. 3Sum
最新推荐文章于 2020-12-27 09:28:24 发布