# twoSum问题的核心思想
![](../pictures/souyisou.png) **labuladong 刷题辅助插件上线,欢迎大家使用,[下载地址](https://github.com/labuladong/fucking-algorithm/releases/tag/1.0),别忘了点个 star**~ 读完本文,你不仅学会了算法套路,还可以顺便去 LeetCode 上拿下如下题目: [1.两数之和](https://leetcode-cn.com/problems/two-sum) [170.两数之和 III - 数据结构设计](https://leetcode-cn.com/problems/two-sum-iii-data-structure-design) **-----------** Two Sum 系列问题在 LeetCode 上有好几道,这篇文章就挑出有代表性的几道,介绍一下这种问题怎么解决。 ### TwoSum I 这个问题的**最基本形式**是这样:给你一个数组和一个整数 `target`,可以保证数组中**存在**两个数的和为 `target`,请你返回这两个数的索引。 比如输入 `nums = [3,1,3,6], target = 6`,算法应该返回数组 `[0,2]`,因为 3 + 3 = 6。 这个问题如何解决呢?首先最简单粗暴的办法当然是穷举了: ```java int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) for (int j = i + 1; j < nums.length; j++) if (nums[j] == target - nums[i]) return new int[] { i, j }; // 不存在这么两个数 return new int[] {-1, -1}; } ``` 这个解法非常直接,时间复杂度 O(N^2),空间复杂度 O(1)。 可以通过一个哈希表减少时间复杂度: ```java int[] twoSum(int[] nums, int target) { int n = nums.length; index======其他语言代码====== [1.两数之和](https://leetcode-cn.com/problems/two-sum) [170.两数之和 III - 数据结构设计](https://leetcode-cn.com/problems/two-sum-iii-data-structure-design) ### python 由[JodyZ0203](https://github.com/JodyZ0203)提供 1. Two Sums Python3 解法代码: 只用一个哈希表 ```python class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # 提前构造一个哈希表 hashTable = {} # 寻找两个目标数值 for i, n in enumerate(nums): other_num = target - n # 如果存在这个余数 other_num if other_num in hashTable.keys(): # 查看是否存在哈希表里,如果存在的话就返回数组 return [i, hashTable[other_num]] # 如果不存在的话继续处理剩余的数 hashTable[n] = i ``` ### javascript [1.两数之和](https://leetcode-cn.com/problems/two-sum) 穷举 ```js /** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function (nums, target) { for (let i = 0; i < nums.length; i++) for (let j = i + 1; j < nums.length; j++) if (nums[j] === target - nums[i]) return [i, j]; // 不存在这么两个数 return [-1, -1]; }; ``` 备忘录 ```js /** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function (nums, target) { let n = nums.length; let index = new Map(); // 构造一个哈希表:元素映射到相应的索引 for (let i = 0; i < n; i++) index.set(nums[i], i); for (let i = 0; i < n; i++) { let other = target - nums[i]; // 如果 other 存在且不是 nums[i] 本身 if (index.has(other) && index.get(other) !== i) return [i, index.get(other)]; } // 不存在这么两个数 return [-1, -1]; }; ``` [170.两数之和 III - 数据结构设计](https://leetcode-cn.com/problems/two-sum-iii-data-structure-design) 哈希集合优化。 ```js class TwoSum { constructor() { this.sum = new Set(); this.nums = []; } // 向数据结构中添加一个数 number add(number) { // 记录所有可能组成的和 for (let n of this.nums) { this.sum.push(n + number) } this.nums.add(number); } // 寻找当前数据结构中是否存在两个数的和为 value find(value) { return this.sum.has(value); } } ```