好久没写C++了,这次把以前用java做过的题用C++再做一次,生疏了很多,各种查语法,心累...
这道题最简单的做法就是用一个哈希表存储数组中的元素和对应的下标。
1、对数组进行一次循环,边插入当前元素nums[i]边查找哈希表中是否已经存在target-nums[i],如果有的话直接返回两个下标;
2、循环一次过后如果没有符合条件的元素要记得抛出一个异常。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
map<int, int> nummap;
for (int i = 0; i < len; i++){
int another = target - nums[i];
if (nummap.count(another)){
vector<int> result = {nummap.at(another), i};
return result;
}
nummap.insert(make_pair(nums[i], i));
}
throw "error";
}
};