版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://cloud.tencent.com/developer/article/1433890
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> result;
int length = nums.size();
for(int i = 0; i < length - 1; i++) {
if(i != 0 && nums[i] == nums[i - 1]) {
continue;
}
int target = 0 - nums[i];
int left = i + 1;
int right = length - 1;
while(left < right) {
if(left != i + 1 && nums[left] == nums[left - 1]) {
left++;
continue;
}
if(right != length - 1 && nums[right] == nums[right + 1]) {
right--;
continue;
}
int sum = nums[left] + nums[right];
if(sum == target) {
vector<int> temp;
temp.push_back(nums[i]);
temp.push_back(nums[left]);
temp.push_back(nums[right]);
result.push_back(temp);
left++;
right--;
}
else if(sum < target) {
left++;
}
else {
right--;
}
}
}
return result;
}
};