I felt like doing an algorithm and found this problem on leetcode
Given an array of integers, find two numbers such that they add up to a specific target num
An O(n) solution in c++ using hash map only exploiting Commutative rule of Addition in real numbers.
class Solution {
public:
vector twoSum(vector& nums, int target) {
unordered_map my_map;
for ( int i = 0 ; i < nums.size(); i++ ){
if(my_map.find(target - nums[i]) != my_map.end()){
return vector {my_map[target - nums[i]], i};
}
my_map[nums[i]] = i ;
}
}
};