/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
// return brute(nums,target);
return memoization(nums, target);
};
// Naive Approach: Brute Force | O(N^2) | O(1)
const brute = (nums, target) => {
for (let i = 0; i < nums.length - 1; i++) {
for (let j = i+1; j < nums.length; j++) {
if (nums[i]+nums[j] === target) return [i,j];
}
}
return []
};
// Memoization: HashMap | O(N) | O(N)
const memoization = (nums, target) => {
const memo = {};
for (let i = 0; i < nums.length; i++) {
if (Number.isInteger(memo[nums[i]])) return [memo[nums[i]], i];
else memo[target - nums[i]] = i;
}
return [];
};