From 4d731f440cf29dde8acd97931c0ff74e96d81349 Mon Sep 17 00:00:00 2001 From: Luke Else Date: Thu, 20 Oct 2022 07:52:34 +0100 Subject: [PATCH] Updated two sum to work with Hashmap --- C++/src/1. Two Sum/TwoSum.cpp | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/C++/src/1. Two Sum/TwoSum.cpp b/C++/src/1. Two Sum/TwoSum.cpp index 7da6bcb..8dcd10b 100644 --- a/C++/src/1. Two Sum/TwoSum.cpp +++ b/C++/src/1. Two Sum/TwoSum.cpp @@ -1,4 +1,5 @@ #include +#include using namespace std; @@ -6,17 +7,20 @@ namespace TwoSum{ class Solution { public: vector twoSum(vector& nums, int target) { + vector res; + map hashMap; for (int i = 0; i < nums.size(); i++) - { - for (int j = i+1; i < nums.size(); j++) - {//Loop through the dataset - if (nums[i] + nums[j] == target) - {//Check sum - return vector() = {i, j}; - } + {//Loop through Dataset + if (hashMap.find(target - nums[i]) != hashMap.end()) + {//See if the remaining value is in the map + res.push_back(i); + res.push_back(hashMap[target - nums[i]]); + return res; } + else + hashMap.emplace(nums[i], i); } - return vector(); + return res; } }; } \ No newline at end of file