LeetCode two-digit sum
problem
Given an integer array nums and an integer target value target, please find the two integers whose sum is the target value in the array and return their array subscripts.
You can assume that each input will only correspond to one answer. However, the same element in the array cannot be used twice.
You can return the answers in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
prompt:
2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109 There
will only be one valid answer
JavaScript code implementation
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
for(var i = 0;i < nums.length-1;i++){
for(var j = i+1;j < nums.length;j++) {
if( nums[i] + nums[j] == target){
return [i,j]
}
}
}
};
Personal idea: Two for loops, loop each number in the array, and then judge whether the sum of the two numbers is equal to the number of the given target. If they are equal, output the subscripts of the two numbers.
ps: If you have any questions, please comment