Leetcode brush notes

Posted May 26, 20201 min read

Difficulty:simple

Given an integer array nums and a target value target, please find the two integers whose sum is the target value in the array and return their array index.

You can assume that each input will only correspond to one answer. However, the same element in the array cannot be used twice.

Example:
Given nums = \ [2, 7, 11, 15 ], target = 9

Because nums \ [0 ]+ nums \ [1 ]= 2 + 7 = 9
So return \ [0, 1 ]
Solution 1:Execution time:636ms; Memory consumption:36.6m

/**
* @param {number []} nums
* @param {number} target
* @return {number []}
* /
var twoSum = function(nums, target) {
const len = nums.length;
let chooses = [];
for(let curr = 0; curr <len; curr ++) {
nums.forEach((value, index) => {
if(len> 2) {
if(curr! = index && nums [curr]+ value === target) {
chooses.push(curr, index);
}
} else {
if(nums [curr]+ value === target) {
chooses.push(curr, index);
}
}
})
}
const choosesSet = [... new Set(chooses)];
return choosesSet;
};

Solution 2:execution time:144ms; memory consumption:35.56m

/**
* @param {number []} nums
* @param {number} target
* @return {number []}
* /
var twoSum = function(nums, target) {
const len = nums.length;
for(let i = 0; i <len; i ++) {
for(let j = i +1; j <len; j ++) {
if(nums [i]+ nums [j]=== target) {
return [i, j]
}
}
}
};