Topic links: Click here
The key solution is to remove repeated, map marking out.
Japanese sentence, if the length is less than the array , return 。
Sort the array.
The first digit enumeration , the double pointer to find a two-digit and
- If the : as it has been sorted, so there can not be equal to three and the number of , exit.
- For repeating elements: skipped, to avoid duplication Solutions
Make a left pointer , the right pointer , when , the execution cycle:
- when , execution cycle, and determines whether or not the left boundary and the right boundary position of the next repeat, deduplication solution. And at the same time to the next position, looking for new solutions
- If greater than , indicating is too large, Left
- If less than , indicating is too small, right
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
int n = nums.size();
for(int i = 0; i < n; ++i)
{
if(nums[i] > 0) break; //若此处大于0,后面不可能找到负数了
if(i > 0 && nums[i] == nums[i-1]) continue; //去重
int pivot = -nums[i];
int L = i + 1, R = n - 1;
while(L<R)
{
if(nums[L]+nums[R]==pivot)
{
ans.push_back({nums[i],nums[L],nums[R]});
++L;
--R;
while(L < R && nums[L] == nums[L-1])
++L;
while(L < R && nums[R] == nums[R+1])
--R;
}
else if(nums[L]+nums[R] < pivot)
{
++L;
}
else
{
--R;
}
}
}
return ans;
}
};