排序+双指针
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
vector<vector<int>> ans;
for(int first = 0; first < n; first++) {
// 避免重复元素
if (first > 0 && nums[first] == nums[first-1]) {
continue;
}
int target = 0 - nums[first];
int third = n - 1;
for (int second = first + 1; second < n; second++) {
// 避免重复元素
if (second > first + 1 && nums[second] == nums[second - 1]) continue;
// 保证second 在 third 左边
while (second < third && nums[second] + nums[third] > target) {
third--;
}
// 如果指针重合就终止
if (second == third) break;
if (nums[second] + nums[third] == target) {
ans.push_back({nums[first], nums[second], nums[third]});
}
}
}
return ans;
}
};
时间复杂度:O(N2)。
空间复杂度:O(logN)。