跳到主要内容

two-sum

https://leetcode.cn/problems/two-sum/description/

// 使用嵌套循环(暴力解法)
function twoSumBruteForce(nums: number[], target: number): number[] {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
return []; // 如果没有找到匹配的对,返回空数组
}

// 使用哈希表(优化解法)
function twoSumHashMap(nums: number[], target: number): number[] {
const numMap = new Map<number, number>();

for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (numMap.has(complement)) {
return [numMap.get(complement)!, i];
}
numMap.set(nums[i], i);
}

return []; // 如果没有找到匹配的对,返回空数组
}

// 测试
console.log(twoSumBruteForce([2, 7, 11, 15], 9)); // 输出: [0, 1]
console.log(twoSumBruteForce([3, 2, 4], 6)); // 输出: [1, 2]
console.log(twoSumHashMap([2, 7, 11, 15], 9)); // 输出: [0, 1]
console.log(twoSumHashMap([3, 2, 4], 6)); // 输出: [1, 2]