Written on November 18, 2023
The classic two sums problem
You are given an array of Integers and another integer targetValue. Write a function that will take these inputs and return the indices of the 2 integers in the array that add up targetValue.
The brute force solution is quite simple. We can use 2 loops to iterate over the array and check if the sum of the 2 numbers is equal to the targetValue. If it is, we can return the indices of the 2 numbers.
We can use a hash table to store the numbers and their indices. Then we can iterate over the array and check if the difference between the targetValue and the current number is in the hash table. If it is, we can return the indices of the 2 numbers.
vector<int> twoSum(vector<int>& nums, int target) {
for(int i = 0; i < nums.size(); i++) {
for(int j = i + 1; j < nums.size(); j++) {
if(nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {};
}
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;
for(int i = 0; i < nums.size(); i++) {
if(hash.find(target - nums[i]) != hash.end()) {
return {hash[target - nums[i]], i};
}
hash[nums[i]] = i;
}
return {};
}