题解 | #牛牛的三元组问题#
牛牛的三元组问题
https://www.nowcoder.com/practice/72c6d735fb1144a2ba162976a4510839
class Solution { public: vector<vector<int> > findTriplets(vector<int>& nums) { sort(nums.begin(), nums.end()); int n = nums.size(); vector<vector<int>> ret; for (int i=0; i<n-2; i++) { if (i>0 && nums[i]==nums[i-1]) continue; int l = i+1; int r = n-1; while (l < r) { int sum = nums[i] + nums[l] + nums[r]; if (sum == 0) { ret.push_back({nums[i], nums[l], nums[r]}); l++; r--; while (l<n-1 && nums[l+1]==nums[l]) l++; while (r>i+1 && nums[r-1]==nums[r]) r--; } else if (sum > 0) { r--; } else { l++; } } } return ret; } };