Created
April 16, 2019 10:23
-
-
Save bunnyadad/1f353d59ac2185aebef024902ef2523d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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