From 1fd8182be534fe3bc80efbd870f947ccd8f24825 Mon Sep 17 00:00:00 2001 From: Fazeel Usmani Date: Thu, 28 Oct 2021 20:57:04 +0530 Subject: [PATCH] Create 28_3sum.cpp --- .../28_3sum.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 10 October LeetCode Challenge 2021/28_3sum.cpp diff --git a/10 October LeetCode Challenge 2021/28_3sum.cpp b/10 October LeetCode Challenge 2021/28_3sum.cpp new file mode 100644 index 0000000..12f5799 --- /dev/null +++ b/10 October LeetCode Challenge 2021/28_3sum.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector> threeSum(vector& nums) { + unordered_map m; + vector> res; + + sort(nums.begin(), nums.end()); + + for (int i = 0; i < nums.size(); i++) + m[nums[i]] = i; + + for (int i = 0; i < nums.size(); i++) { + if (i > 0 && nums[i] == nums[i-1]) continue; + + for (int j = i+1; j < nums.size(); j++) { + if (j != i+1 && nums[j] == nums[j-1]) continue; + + if (m[-(nums[i] + nums[j])] > j) + res.push_back({nums[i], nums[j], -(nums[i] + nums[j])}); + + } + } + return res; + } +};