class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
int n=nums.size();
if(n<3){
return ans;
}
sort(nums.begin(),nums.end());
for(int p=0;p<n-2;++p){
if(p>0&&nums[p]==nums[p-1]) continue;
int left=p+1;
int right=n-1;
while(left<right){
int m=nums[left]+nums[p]+nums[right];
if(m==0){
vector<int> temp;
temp.push_back(nums[p]);
temp.push_back(nums[left]);
temp.push_back(nums[right]);
ans.push_back(temp);
left++;
right--;
while(left<right&&nums[left]==nums[left-1]){
left++;
}
while(left<right&&nums[right]==nums[right+1]){
right--;
}
}else if(m<0){
left++;
while(left<right&&nums[left]==nums[left-1]){
left++;
}
}else{
right--;
while(left<right&&nums[right]==nums[right+1]){
right--;
}
}
}
}
return ans;
}
};
15 3Sum
最新推荐文章于 2015-12-16 12:15:32 发布