题目
思路
题目大意:给一个数组和一个目标值,问数组中是否存在两个数之和等于目标值;
将数组的数进行hash计数,从小到大一个个枚举;
注意:要考虑自身与自身相加等于目标值的情况;
尽管每个数都不会超过500,但是目标值会超过500,此时如果hash数组只开了510,会导致越界;
代码
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1005;
int num[maxn];
int main()
{
memset(num, 0, sizeof(num));
int n, m, t;
scanf("%d%d", &n, &m);
//统计每个数字出现的次数
for(int i = 0; i < n; i ++){
scanf("%d", &t);
num[t] ++;
}
//从小到大比较有没有合适的
for(int i = 0; i < maxn; i ++){
//出现过才会进行判断
if(num[i] != 0){
//先讨论自身+自身=m
if(m - i == i){
if(num[i] >= 2){
printf("%d %d", i, i);
return 0;
}
}
else if(num[m - i] != 0){
printf("%d %d", i, m - i);
return 0;
}
}
}
printf("No Solution\n");
system("pause");
return 0;
}