LeetCode每日一练
two_sum
/*
* @Author: fox
* @Date: 2022-04-18 20:46:49
* @LastEditors: fox
* @LastEditTime: 2022-04-18 21:49:00
* @Description: https://leetcode.com/problems/two-sum/
*/
const twoSum = (nums, target) => {
// 1 创建一个 Map
const map = new Map()
// 2 遍历数组 nums
for (let i = 0; i < nums.length; i++) {
// 2.1 计算 target 与 nums[i] 的差值
const res = target - nums[i]
// 2.2 如果差值在map中,返回数组
if (map.has(res)) {
return [map.get(res), i]
}
// 2.3 如果差值不在map中,将nums[i]和i存储到map中
map.set(nums[i], i)
}
return []
};
const nums = [2, 7, 11, 15]
const target = 9
const res = twoSum(nums, target)
console.log(res) // [ 0, 1 ]
原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/246185.html