1、暴力解法
两个嵌套for循环可以解决(188ms)
2、利用map数据结构
用给出的矩阵构建map,只需要用两个并列的for循环(12ms)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> hash;
map<int, int>::iterator it;
vector<int> result;
for(int i = 0; i < nums.size(); i++)
{
hash.insert({nums[i], i});
}
for(int j = 0; j < nums.size(); j++)
{
it = hash.find(target - nums[j]);
int m = it->second;
if(it != hash.end() && m != j)
{
result.push_back(j);
result.push_back(m);
hash.erase(nums[j]);
hash.erase(nums[m]);
}
}
return result;
}
};