找数字第一反应二分,第二反应hash
#include <iostream>
#include <map>
using namespace std;
int result[2] = {0};
void gettarget(int *pArray, int len, int target)
{
result[0] = result[1] = -1;
map<int, int> tag;
for (int i = 0; i < len; i++)
{
int key = target - pArray[i];
auto it = tag.find(key);
if (it != tag.end())
{
result[0] = i;
result[1] = it->second;
return;
}
tag.insert(make_pair(pArray[i], i));
}
}
int main() {
int array[] = {1,3,6,34,-23,45,345,1};
gettarget(array, 8, 11);
cout << result[0] << " " << result[1] << endl;
int array2[] = {1,3,67,87,23,45,67};
gettarget(array2, 7, 154);
cout << result[0] << " " << result[1] << endl;
return 0;
}