Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
这道题是让在一个数组中找到两个相加能够与给定目标数相等的下标。可以是用map结构,然后遍历数组中的元素,拿到数值之后将其作为key在map中查找。如果在map中没有找到这个数值,则将目标数减去这个数值得到的结果作为key,这个数值的下标作为value存放在map中,然后继续往后面遍历。如果遇到了另一个数正好等于目标数减去刚才那个数,那么这个数作为key在map中就会存在。比如:目标数为3,数组第一个数为1,那么存放在map中的元素就是<2,0>,然后第二个数为2,此时发现map中已经有了<2,0>那么当前的下标和map中的下标就是我们所要求的结果。
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ret;
unordered_map<int,int> m;
if (!nums.empty()) {
int i;
for (i = 0; i < nums.size(); i++) {
if (m.find(nums[i]) == m.end()) {//此时map中不存在此hash
m[target-nums[i]] = i;
} else {
ret.push_back(m[nums[i]]);//另一个的下标索引
ret.push_back(i);//此时的下标索引
return ret;
}
}
}
return ret;
}
};
int main() {
Solution s;
vector<int> num;
num.push_back(2);
num.push_back(7);
num.push_back(11);
num.push_back(15);
vector<int> ret = s.twoSum(num,9);
cout << ret[0] << " " << ret[1];
}
运行结果可能有误差。