Skip to content

Instantly share code, notes, and snippets.

@bunnyadad
Created April 16, 2019 10:23
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 bunnyadad/1f353d59ac2185aebef024902ef2523d to your computer and use it in GitHub Desktop.
Save bunnyadad/1f353d59ac2185aebef024902ef2523d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> threeSum(vector<int> nums)
{
if (nums.size() < 3) return{};
sort(nums.begin(), nums.end());
vector<vector<int>> output;
for (size_t i = 0; i < nums.size() - 2; i++)
{
size_t front = i + 1;
size_t back = nums.size() - 1;
int sum = 0 - nums[i];
while (front < back)
{
if (nums[front] + nums[back] == sum)
{
output.push_back({ nums[i], nums[front], nums[back] });
while ((front < back) && nums[front] == nums[front + 1]) front++;
while ((back < front) && nums[front] == nums[back - 1]) back--;
front++; back--;
}
else if (nums[front] + nums[back] < sum) front++;
else back--;
}
while ((i < nums.size() - 2) && nums[i] == nums[i + 1]) i++;
}
return output;
}
};
int main()
{
Solution a;
auto b = a.threeSum({ 1, -1, -1, 0 });
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment