Related leetCode question:
https://leetcode.com/problems/two-sum/description/
Here is my original answer, which uses double for-loop. It is no ideal in terms of iteration time, because there is no breaks and it iterates two loops 😧
var twoSum = function(nums, target) {
let result = [];
for(let i = 0; i < nums.length -1; i++ ) {
const val1 = nums[i];
const nextIndice = i + 1;
const newArr = nums.slice(nextIndice);
for(let j =0 ; j < newArr.length; j++) {
const sum = val1 + newArr[j];
if(sum === target) {
result = [i, nextIndice + j];
}
}
}
return result;
We can make it more performative algorithm using Map object!
The return value we are interested in is getting array of 'index' that satisfies condition. Thus, first step is to create table having index as value (invert). So we can get the index using get
method from Map class instance.
const map = new Map();
map.set(nums[i], i) // index is value in Map object
The value we are interested in is that the sum of two values are equal to 'target', and we will iterate through nums array.
// target = nums[i] + val
// same as val = target - nums[i]
if(map.has(target - nums[i])) {
return [map.get(target - nums[i]), i] // this is what we are looking for! 🌟
} else {
map.set(nums[i], i) // update table
}
Again, here we use Map object to avoid double for-loops!
Top comments (0)