1. Two Sum
Description
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
My Solution
Source Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
let twoSum = function(nums, target) {
let result = null;
//the inner loop does not need to iterate over the numbers already iterated over in the outer loop
for (let index1 = 0; index1 < nums.length; index1++) {
for (let index2 = index1 + 1; index2 < nums.length; index2++) {
if (nums[index1] + nums[index2] === target) {
return [index1, index2];
}
}
}
return result;
};
Analysis
My solution is extremely basic. We start with the first number in the array and then check it against each remaining number to see if the sum is equal to the target. This is repeated until a match is found.