Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created October 22, 2018 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/66e68be7bd87d34a4797fd15850f4fdc to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/66e68be7bd87d34a4797fd15850f4fdc to your computer and use it in GitHub Desktop.
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int len = nums.size();
vector<vector<int>> finalResult;
std::sort(nums.begin(), nums.end());
if(len <= 2)
return finalResult;
for(int i = 0; i < len - 2; i++)
{
int a = nums[i];
if(a > 0)
break;
if(i > 0 && a == nums[i-1])
continue;
for(int j = i + 1, k = len - 1; j < k;)
{
int b = nums[j];
int c = nums[k];
int value = a + b + c;
if(value == 0)
{
finalResult.push_back({a,b,c});
while(j<len - 1 && b == nums[++j]);
while(c> 0 && c == nums[--k]);
}
else if(value > 0)
k--;
else
j++;
}
}
return finalResult;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment