Home » JavaScript » LeetCode Two Sum JavaScript solutions

LeetCode Two Sum JavaScript solutions

started the first question on the LeetCode brush problem: Two Sum


1, idea 1: use regular to match data and get index:


/**
* @param, {number[]}, nums
* @param, {number}, target
* @return {number[]}
* /
Var twoSum = function (nums, target) {
"Var str=", "+nums.toString" () +",";
For (VaR i=0; iVar info=target-nums[i];
VaR, patt1 = new, RegExp ("," +info+ "," "));
Var result = patt1.test (STR);
Var init=nums.indexOf (info)
If (result & & init! =i) {
Return, [i, init];
}
}
};
. Results: the... Is not ideal, "LeetCode Two alt= ></p>

thinking 2: use the indexOf function to get subscript


/**
* @param, {number[]}, nums
* @param, {number}, target
* @return {number[]}
* /
Var twoSum = function (nums, target) {
Var k=0;
For (VaR i=0; iK=nums.indexOf (target-nums[i]);
If (K =-1 & & K!! {=i)
Return, [i, k];
}
}
}.
results: in general, there can be improvements,


LeetCode Two Sum JavaScript solutions ofIdea 3: array subscript and numeric inversion


/**
* @param, {number[]}, nums
* @param, {number}, target
* @return {number[]}
* /
Var twoSum = function (nums, target) {
Var k=[];
Var j=0;
Var l=0;
For (VaR i=0; iL=nums[i];
J=k[target-l];
If (J, =undefined) {
Return, [j, i];
}
K[l]=i;
}
},
results: a step further, silly water


LeetCode Two Sum JavaScript solutions of

thinking 4: on the basis of the idea 3, reduce the operation of array subscript


/**
* @param, {number[]}, nums
* @param, {number}, target
* @return {number[]}
* /
Var twoSum = function (nums, target) {
Var k=[];
For (VaR i=0; iVar l=nums[i];
Var j=k[target-l];
If (J, =undefined) {
Return, [j, i];
}
K[l]=i;
}
},
result: better than the last one, lost, no difference,


LeetCode Two Sum JavaScript solutions ofThinking 5; of course, also learn from the use of other objects for data storage,


/**
* @param, {number[]}, nums
* @param, {number}, target
* @return {number[]}
* /
Var twoSum = function (nums, target) {
Var k={};
For (VaR i=0; iVar l=nums[i];
Var j=k[target-l];
If (J, =undefined) {
Return, [j, i];
}
K[l]=i;
}
},
results: feel much faster, within 100ms,


LeetCode Two Sum JavaScript solutions of

summary:


The difference between 4 and 5

starting thinking ideas is only a place (the difference between array and object), but the difference between them is very large, this is why? Because the array is a special object... Index array is ordered data sets, but the object is no sequence.







Latest