Two Sum
Descrption
original description
Solutions
Brute Force
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
for (let i = 0; i < nums.length - 1; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) { // check every possible case
return [i, j];
}
}
}
return [-1, -1] // will never touch
};
- Time Complexity: O(n^2)
- Space Complexity: O(1)
Cache Diff by Map
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
const cache = {}
for (let i = 0; i < nums.length; i++) {
const cachedIndex = cache[target - nums[i]];
if (cachedIndex !== undefined) { // found cached diff, return directly
return [cachedIndex, i];
}
cache[nums[i]] = i; // otherwise cache it for later use
}
return [-1, -1];
};
- Time Complexity: O(n)
- Space Complexity: O(n)