# 引言
题目链接:https://leetcode.com/problems/two-sum/description/
# 题目大意
给出一个序列和一个目标值,判断序列中是否有两个数相加等于序列值
You may assume that each input would have exactly one solution, and you may not use the same element twice
因此认为给出序列必有解,并且不存在两个相同的元素
# 题解
# 一句话题解
利用 unordered_map
做好值和序号映射,在初始化 map 的时候用当前值和 target
和当前值的差在 map 中做校验即可
复杂度 O(n)
# AC 代码
c++
版本
class Solution | |
{ | |
public: | |
vector<int> twoSum(vector<int> &nums, int target) | |
{ | |
unordered_map<int, int> iMap; | |
vector<int> rVec; | |
for (int i = 0; i < nums.size(); ++i) | |
{ | |
if (iMap.count(target - nums[i])) | |
{ | |
rVec.push_back(iMap[target - nums[i]]); | |
rVec.push_back(i); | |
} | |
iMap[nums[i]] = i; | |
} | |
return rVec; | |
} | |
}; |
go
版本
func twoSum(nums []int, target int) []int { | |
numsMaper := make(map[int]int) | |
for i, n := range nums { | |
_, ok := numsMaper[target-n] | |
if ok { | |
return []int{numsMaper[target-n], i} | |
} | |
numsMaper[n] = i | |
} | |
return nil | |
} |