AcWing 800. 数组元素的目标和
原题链接
简单
作者:
Value
,
2020-04-27 11:19:27
,
所有人可见
,
阅读 443
unordered_map
#include <iostream>
#include <unordered_map>
using namespace std;
const int N = 1E5 + 10;
int a[N];
unordered_map<int, int> mp;
int main(){
int n, m, x; cin >> n >> m >> x;
for(int i = 0; i < n; i ++ ){
int tmp; scanf("%d", &tmp);
mp.insert({tmp, i});
}
for(int i = 0; i < m; i ++ ) scanf("%d", &a[i]);
for(int i = 0; i < m; i ++ ){
if(mp.find(x - a[i]) != mp.end()){
cout << mp[x - a[i]] << ' ' << i << endl;
break;
}
}
return 0;
}
双指针(输入数据有序)
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 1E5 + 10;
int a[N], b[N];
int main(){
int n, m, x; cin >> n >> m >> x;
for(int i = 0; i < n; i ++ ) scanf("%d", &a[i]);
for(int i = 0; i < m; i ++ ) scanf("%d", &b[i]);
int i = 0, j = m - 1;
while(i < n && j >= 0){
int sum = a[i] + b[j];
if(sum == x) break;
else if(sum < x) i ++ ;
else j -- ;
}
cout << i << ' ' << j << endl;
return 0;
}