给定一个乱序数组a,找到所有两个和为target的数组下标index1,index2
使用hash_map,时间复杂度为o(n),空间复杂度为o(n).
Exp:
a{ 2, 3, 1, 4, 5, 6, 7 },target=6;
输出:0 3
2 4
#include <iostream>
#include <vector>
#include <hash_map>
using namespace std;
vector<vector<int>> getSum(vector<int>a, int target){
vector<vector<int>>res;
hash_map<int, int>map;
for (int i = 0; i < a.size(); i++){
map[a[i]] = i;
}
for (int i = 0; i < a.size(); i++){
if (map[target - a[i]] != NULL&&map[target-a[i]]!=i){
vector<int>temp;
temp.push_back(i);
temp.push_back(map[target-a[i]]);
map[a[i]] = NULL;
map[target - a[i]] = NULL;
res.push_back(temp);
}
}
return res;
}
int main(){
vector<int>a{ 2, 3, 1, 4, 5, 6, 7 };
int target=6;
vector<vector<int>>res;
res = getSum(a, target);
for (int i = 0; i < res.size(); i++){
int j;
for (j = 0; j < res[0].size(); j++){
cout << res[i][j]<<" ";
}
cout << endl;
}
}