From 8a167ebab112b4f7701bfc84db5bdd2d46f0b1ff Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Thu, 20 Feb 2025 23:35:00 +0800 Subject: [PATCH] feat: 18_4sum --- 18_4sum/main.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 18_4sum/main.cpp diff --git a/18_4sum/main.cpp b/18_4sum/main.cpp new file mode 100644 index 0000000..627891a --- /dev/null +++ b/18_4sum/main.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; + +class Solution { + public: + vector> fourSum(vector& nums, int target) { + set> resultSet; + + sort(nums.begin(), nums.end()); + + for (int i = 0; i < nums.size(); i++) { + for (int j = i + 1; j < nums.size(); j++) { + int l = j + 1, r = nums.size() - 1; + + while (l < r) { + long long sum = (long long)nums[i] + nums[j] + nums[l] + nums[r]; + if (sum < target) { + l++; + } else if (sum > target) { + r--; + } else { + resultSet.insert({nums[i], nums[j], nums[l], nums[r]}); + l++; + } + } + } + } + + vector> result; + for (auto& e : resultSet) { + result.emplace_back(e); + } + + return result; + } +};