这里保证1.元素a不会重复。2.所有解都是有序的。3.b和c元素不重复。所以解不会重复。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
std::vector<std::vector<int>> result;
if (nums.size() < 3) return result;
std::sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 2; ++i) {
if (i > 0 && nums[i] == nums[i-1]) continue; // Skip duplicate numbers
int left = i + 1;
int right = nums.size() - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.push_back({nums[i], nums[left], nums[right]});
while (left < right && nums[left] == nums[left+1]) left++; // Skip duplicates
while (left < right && nums[right] == nums[right-1]) right--; // Skip duplicates
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
};