这道题主要是优化三重循环。题目要求是不重复的结果,将数组进行排序,相同的元素彼此相邻,在遍历中跳过相邻的相同元素,避免得到重复的结果。循环的思想依旧是固定其中两个数,遍历寻找符合条件的第三个数。第一层和第二层循环分别用来确定第一个数和第二个数,这两层循环利用排序的结果,跳过重复的元素,去掉重复的结果。第三个元素的循环从最大值逆序遍历,避免重复遍历first和second遍历过的元素。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
int n = nums.size();
for(int first = 0; first < n; first++)
{
if(first>0 && nums[first]==nums[first-1]) continue;
int third = n-1;
int target = -nums[first];
for(int second = first + 1; second < n; second++)
{
if(second>first+1 && nums[second]==nums[second-1]) continue;
while(second<third && nums[second]+nums[third]>target) third--;
if(second==third) break;
if(nums[second]+nums[third] == target)
res.push_back({nums[first], nums[second], nums[third]});
}
}
return res;
}
};
425




被折叠的 条评论
为什么被折叠?



