Javascript | 初级算法
No.1 两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
// =========== 解题思路 ==========
// 首尾相减取差值,遍历数组差是否存在
// target - nums[0]
function twoNums (nums, target) {
for(let i = 0; i< nums.length; i++) {
const _firstNum = nums[i];
const _result = target - firstNum;
const _baseArry = nums.slice(i+1);
_baseArry.forEach(el => {
if (_result === el) {
const _index = nums.indexOf(el);
console.log('差值',_result, '结果值',el, '下标值',_index);
}
});
}
}
// all time: 0.288818359375 ms
function twoNums (nums, target) {
let hash = {};
for (let i = 0; i < nums.length; i++) {
if (hash[target - nums[i]] !== undefined) {
console.log(i, hash[target - nums[i]]);
return [i, hash[target - nums[i]]];
}
hash[nums[i]] = i;
}
return [];
}
// all time: 0.166748046875 ms
twoNums([1, 3, 5, 7, 9], 10);
文章目录
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。