Given an array of integers and I want to return indices of the two numbers such that they add up to a specific target. Assuming that each input would have exactly one solution, and I haven't used the same element twice.
I am using the brute force approach to Loop through each element x and find if there is another value that equals to target−x
code snippet:
var twoSum = function(nums, target) {
for(var i ; i<nums.length ; i++){
for(var j = i + 1; j<nums.length ; j++){
if (nums[j]==target-nums[i]){
// This is where I want to return new array
return
}
}
}
};
asked Dec 18, 2017 at 5:34
Philip Mutua
6,99914 gold badges49 silver badges101 bronze badges
1 Answer 1
You just want to return the two indices?
return [i, j];
answered Dec 18, 2017 at 5:36
Robby Cornelissen
98.6k23 gold badges154 silver badges180 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Rajesh Dixit
May be its an opinionated comment, but I guess this could have been a comment
Philip Mutua
is it appropriate if I use
new Array(i,j);Charlie Martin
Always prefer array literals [] to using the constructor in javascript. Same goes with objects. Use {} instead of new Object()
lang-js
for(var i ;isn't going to work, you need to initialise i with a number value:for(var i=0;, otherwise you're trying to do++undefined. You haven't actually said what the problem is or any errors you get.++undefinedproducesNaN, then++NaNcontinues to produceNaNsoi<nums.lengthis always false (sinceNaN < anythingis always false.