Skip to content

Commit

Permalink
Added Three Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 2, 2023
1 parent 5376c37 commit 3437b1d
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion Medium/ThreeSum/include/solution.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,28 @@ class Solution {
public:
static auto three_sum(std::vector<int32_t> &nums)
-> std::vector <std::vector<int32_t>> {

std::ranges::sort(nums);
std::set<std::vector<int32_t>> unique_rows;

for (std::size_t i = 0; i < nums.size() - 2; ++i) {
std::size_t left = i + 1;
std::size_t right = nums.size() - 1;

while (left < right) {
int32_t sum = nums[i] + nums[left] + nums[right];

if (sum == 0) unique_rows.insert({nums[i],
nums[left],
nums[right]}),
++left, --right;
else if (sum < 0) ++left;
else --right;
}
}

std::vector<std::vector<int32_t>> result(unique_rows.begin(),
unique_rows.end());

return result;
}
};

0 comments on commit 3437b1d

Please sign in to comment.