1. 两数之和
题目
方法思路
hashMap
- 哈希表中存
数组中的数
到索引
的映射关系
代码
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashMap;
hashMap[nums[0]] = 0;
vector<int> ans;
for (int i = 1; i < nums.size(); i++) {
if (hashMap.find(target - nums[i]) != hashMap.end()) {
ans.push_back(hashMap[target - nums[i]]);
ans.push_back(i);
break;
} else {
hashMap[nums[i]] = i;
}
}
return ans;
}
};
官方题解:两数之和题解