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
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
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
未经授权禁止转载,违者必究!