Updated two sum to work with Hashmap

This commit is contained in:
Luke Else 2022-10-20 07:52:34 +01:00
parent 9a23232cb8
commit 4d731f440c

View File

@ -1,4 +1,5 @@
#include <vector> #include <vector>
#include <map>
using namespace std; using namespace std;
@ -6,17 +7,20 @@ namespace TwoSum{
class Solution { class Solution {
public: public:
vector<int> twoSum(vector<int>& nums, int target) { vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
map<int, int> hashMap;
for (int i = 0; i < nums.size(); i++) for (int i = 0; i < nums.size(); i++)
{ {//Loop through Dataset
for (int j = i+1; i < nums.size(); j++) if (hashMap.find(target - nums[i]) != hashMap.end())
{//Loop through the dataset {//See if the remaining value is in the map
if (nums[i] + nums[j] == target) res.push_back(i);
{//Check sum res.push_back(hashMap[target - nums[i]]);
return vector<int>() = {i, j}; return res;
} }
else
hashMap.emplace(nums[i], i);
} }
} return res;
return vector<int>();
} }
}; };
} }