LeetCode 两数之和算法题解 All In One
LeetCode 两数之和算法题解 All In One
js / ts 实现两数之和
1. Two Sum
https://leetcode.com/problems/two-sum/description/
// 1. 双重循环 ✅
function twoSum(nums: number[], target: number): number[] {
let temp;
for (let i = 0; i < nums.length; i++){
temp = nums[i]
for (let j = i + 1; j < nums.length; j++){
if (temp + nums[j] === target){
return [i, j].sort()
}
}
}
}
// 2. 对象字典 ✅
// function twoSum(nums: number[], target: number): number[] {
// const dict = {}
// for (const [i, item] of Object.entries(nums)) {
// const temp = target - item;
// if(dict[temp]) {
// return [i, dict[temp]].sort()
// } else {
// dict[item] = i;
// }
// }
// };
// 3. Map 字典 ✅
// function twoSum(nums: number[], target: number): number[] {
// const dict = new Map()
// for (const [i, item] of Object.entries(nums)) {
// const temp = target - item;
// if(dict.has(temp)) {
// return [i, dict.get(temp)].sort()
// } else {
// dict.set(item, i)
// }
// }
// };
// 3. hack 一次替换 ✅
// function twoSum(nums: number[], target: number): number[] {
// for (const [i, item] of Object.entries(nums)) {
// const temp = target - item;
// const arr = [...nums]
// // X 替换
// arr[i] = `X`;
// const index = arr.indexOf(temp)
// if(index !== -1) {
// return [parseInt(i), index].sort()
// }
// }
// };
/*
Testcase Source
[2,7,11,15]
9
[3,2,4]
6
[3,3]
6
[2,5,5,11]
10
[-1,-2,-3,-4,-5]
-8
*/
两数之和原理 图解
HashMap
/ Map
字典
// 2. HashMap 解法 O(n)
function twoSum(nums: number[], target: number): number[] {
const map = new Map();
let result:number[] = [];
for(let i = 0; i < nums.length; i++) {
let rest = target - nums[i];
// 7 = 9 - 2
// 2 = 9 - 7
if(map.has(rest)) {
result = [i, map.get(rest)];
break;
} else {
map.set(nums[i], i);
}
}
// console.log(`map`, [...map])
// console.log(`result`, result)
return result.sort((a, b) => a - b > 0 ? 1 : -1);
};
1. Two Sum
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2022-08-17
* @modified
*
* @description 1. Two Sum
* @description 1. 两数之和
* @difficulty Easy
* @ime_complexity O(n)
* @space_complexity O(n)
* @augments
* @example
* @link https://leetcode.com/problems/two-sum/
* @link https://leetcode.cn/problems/two-sum/
* @solutions
*
* @best_solutions
*
*/
export {};
const log = console.log;
// 1. 暴力解法 O(n^2)
function twoSum(nums: number[], target: number): number[] {
let result:number[] = [];
for(let i = 0; i < nums.length; i++) {
for(let j = i + 1; j < nums.length; j++) {
if(nums[i] + nums[j] === target) {
result = [i, j];
break;
}
}
}
return result;
};
// 2. HashMap 解法 O(n)
function twoSum(nums: number[], target: number): number[] {
const map = new Map();
let result:number[] = [];
for(let i = 0; i < nums.length; i++) {
let rest = target - nums[i];
// 7 = 9 - 2
// 2 = 9 - 7
if(map.has(rest)) {
result = [i, map.get(rest)];
break;
} else {
map.set(nums[i], i);
}
}
// console.log(`map`, [...map])
// console.log(`result`, result)
return result.sort((a, b) => a - b > 0 ? 1 : -1);
};
type TestCasesO = {
inputs: [number[], number];
result: number[];
desc: string;
}
// interface TestCasesI extends Array<any>{
// [index: number]: TestCasesO;
// }
interface TestCasesI extends Array<TestCasesO>{
// [index: number]: TestCasesO;
}
// 测试用例 test cases
const testCases: TestCasesI = [
{
inputs: [[2,7,11,15], 9],
result: [0,1],
desc: 'value equal to [0,1]',
},
{
inputs: [[3,2,4], 6],
result: [1,2],
desc: 'value equal to [1,2]',
},
{
inputs: [[3,3], 6],
result: [0,1],
desc: 'value equal to [0,1]',
},
];
for (const [i, testCase] of testCases.entries()) {
const [first, second] = testCase.inputs;
const result = twoSum(first, second);
log(`test case i result: \n`, result.join('') === testCase.result.join('') ? `passed ✅` : `failed ❌`, result);
// log(`test case i =`, testCase);
}
// npx ts-node ./001\ two-sum.ts
https://leetcode.com/problems/two-sum/
https://leetcode.cn/problems/two-sum/
leetcode 题解 / LeetCode Solutions
https://www.youtube.com/results?search_query=+Leetcode+1
https://www.youtube.com/playlist?list=PLamwFu9yMruCBtS2tHUD77oI_Wsce-syE
https://www.youtube.com/channel/UCftIXZeipv4MTVwmfFphtYw/videos
https://github.com/neetcode-gh/leetcode/blob/main/javascript/1-Two-Sum.js
https://github.com/neetcode-gh/leetcode/blob/main/typescript/1-Two-Sum.ts
类似问题
LeetCode
- 3Sum
https://leetcode.com/problems/3sum/
https://leetcode.cn/problems/3sum/
- 3Sum Closest
https://leetcode.com/problems/3sum-closest/
https://leetcode.cn/problems/3sum-closest/
- 4Sum
https://leetcode.com/problems/4sum/
https://leetcode.cn/problems/4sum/
demos
refs
https://www.cnblogs.com/xgqfrms/p/13752388.html
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16600519.html
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
2021-08-18 vue 使用 object 作为循环中的响应式的数据源 All In One
2021-08-18 Chrome Array bug All In One
2021-08-18 OpenAI Codex All In one
2020-08-18 how to using Linux pipe command output another command's help content to a file
2020-08-18 hackr.io & Programming Courses & Programming Tutorials
2020-08-18 SQL Tutorials & MySQL & SQL Server
2020-08-18 How to use PyPI to publish a Python package All In One