力扣链接:1.两数之和
难度:⭐
解题关键词:数组
、map
解题思路:创建一个数字和 map 的关系,判断当前数字要求和的另一个数字在不在 map 中,如果在直接返回,不在就在 map 中添加当前元素的映射。
typescript
function twoSum(nums: number[], target: number): number[] {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const findValue = target - nums[i];
// 找到另一个加和的元素
if (map.has(findValue)) {
return [map.get(findValue), i];
} else {
map.set(nums[i], i);
}
}
return [];
}