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 <map>
using namespace std;
@ -6,17 +7,20 @@ namespace TwoSum{
class Solution {
public:
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 j = i+1; i < nums.size(); j++)
{//Loop through the dataset
if (nums[i] + nums[j] == target)
{//Check sum
return vector<int>() = {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<int>();
return res;
}
};
}