1. two sum
Closed this issue · 3 comments
lf7817 commented
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].
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
};
lf7817 commented
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
};
lf7817 commented
Beat: 44.34%
Runtime: 120ms
Time Complexity : O(n²)
Space Complexity: O(1)
/**
* @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) {
return [i, j]
}
}
}
};
lf7817 commented
Beat: 100.00%
Runtime: 52ms
Time Complexity : O(n)
Space Complexity: O(n)
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const obj = {};
for(let i = 0; i < nums.length; i ++) {
const tmp = target - nums[i];
if (obj.hasOwnProperty(nums[i])) {
return [obj[nums[i]], i]
}
obj[tmp] = i;
}
};