0001. 两数之和
题目地址(1. 两数之和)
https://leetcode-cn.com/problems/two-sum
题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。示例:给定 nums = [2, 7, 11, 15], target = 9因为 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1]
前置知识
哈希表
公司
字节
百度
腾讯
adobe
airbnb
amazon
apple
bloomberg
dropbox
facebook
linkedin
microsoft
uber
yahoo
yelp
思路
最容易想到的就是暴力枚举,我们可以利用两层 for 循环来遍历每个元素,并查找满足条件的目标元素。
伪代码:
for(int i = 0; i < n; i++) { for(int j = 0; j < i;j ++){ if (nums[i] + nums[j] == target) return [j, i] }}
不过这样时间复杂度为 O(N^2),空间复杂度为 O(1),时间复杂度较高,我们要想办法进行优化。
这里我们可以增加一个 Map 记录已经遍历过的数字及其对应的索引值。这样当遍历一个新数字的时候就去 Map 里查询target 与该数的差值 diff 是否已经在前面的数字中出现过。如果出现过,说明 diff + 当前数 = target,我们就找到了一组答案。
关键点
求和转换为求差
借助 Map 结构将数组中每个元素及其索引相互对应
以空间换时间,将查找时间从 O(N) 降低到 O(1)
代码
语言支持:JS, Go,CPP,Java,Python
/** * @param {number[]} nums * @param {number} target * @return {number[]} */const twoSum = function (nums, target) { const map = new Map(); for (let i = 0; i < nums.length; i++) { const diff = target - nums[i]; if (map.has(diff)) { return [map.get(diff), i]; } map.set(nums[i], i); }};
Go Code:
func twoSum(nums []int, target int) []int {m := make(map[int]int)for i, _ := range nums {diff := target - nums[i]if j, ok := m[diff]; ok {return []int{i, j}} else {m[nums[i]] = i}}return []int{}}
CPP Code:
class Solution {public: vector<int> twoSum(vector<int>& A, int target) { unordered_map<int, int> m; for (int i = 0; i < A.size(); ++i) { int t = target - A[i]; if (m.count(t)) return { m[t], i }; m[A[i]] = i; } return {}; }};
Java Code:
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; ++i) { if (hashtable.containsKey(target - nums[i])) { return new int[]{hashtable.get(target - nums[i]), i}; } hashtable.put(nums[i], i); } return new int[0]; }}
Python Code:
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashtable = dict() for i, num in enumerate(nums): if target - num in hashtable: return [hashtable[target - num], i] hashtable[nums[i]] = i return []
复杂度分析
时间复杂度:$O(N)$
空间复杂度:$O(N)$
更多题解可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 40K star 啦。
关注公众号力扣加加,努力用清晰直白的语言还原解题思路,并且有大量图解,手把手教你识别套路,高效刷题。

最后更新于
这有帮助吗?