Topic describes
Given an array of integers nums and a target value target, find the two integers in the array and the target values and return their array subscripts.
You can assume that there is only one answer for each type of input. However, you cannot reuse the same elements in this array.
Given nums = [2, 7, 11, 15], target = 9Copy the code
Analysis of the
Points to pay attention to
- It returns the subscript instead of two numbers
- You can’t reuse numbers in an array
algorithm
The double cycle judgment target value of the violence point minus the element of the outer cycle equals the element of the inner cycle if equals returns the subscript
var twoSum = function (nums, target) {
for (var i = 0; i < nums.length; i++) {
for (var j = i + 1; j < nums.length; j++) {
if (nums[j] === target - nums[i]) {
return [i, j]
}
}
}
}
Copy the code
It’s going to be a little bit more complicated to loop twice and you can trade space for time and use arrays or objects to find things
var twoSum = function(nums, target) { var temp = []; Var temp ={};for(var i=0; i<nums.length; i++){ var dif = target - nums[i];if(temp[dif] ! = undefined){return[temp[dif],i]; } temp[nums[i]] = i; }};Copy the code
But there is one detail to note when using arrays
If you have a better algorithm or opinion, please leave a comment