题目链接:
https://pintia.cn/problem-sets/994805342720868352/problems/994805432256675840
题目分析:
1,two pointers
本题可先将该序列进行排序,然后,设置两个分别指向第一个和最后一个的下标i,j;
若有c[i] + c[j] == m,则输出c[i]、c[j],若c[i] + c[j] < m,则将i++,若c[i] + c[j] > m,则将j--。
2,hash()
hashtable[i]表示数字i出现的次数。若hashtable[i]和hashtable[m-i]同时大于0,则说明有数对i和m-i满足题意。注意的是,若i == m - i,则需要hashtable[i]大于1。
参考代码:
two pointer:
#include <bits/stdc++.h>
using namespace std;
int c[100010], n, m;
int main(){
scanf("%d %d",&n, &m);
for(int i = 0; i < n; i++){
scanf("%d",&c[i]);
}
sort(c, c + n);
int i = 0, j = n - 1;
for(; i < j; ){
if(c[i] + c[j]==m) {
printf("%d %d\n",c[i], c[j]);
break;
}else if(c[i] + c[j] > m){
j--;
}else{
i++;
}
}
if(i==j) printf("No Solution\n");
return 0;
}
hash:
#include <bits/stdc++.h>
using namespace std;
int hashtable[1010];
int main(){
int n, m, a;
cin >> n >> m;
for(int i = 0; i < n; i++){
cin >> a;
hashtable[a]++;
}
bool flag = false;
for(int i = 1; i <= m/2; i++){
if(hashtable[i] && hashtable[m-i]){
if(m - i== i && hashtable[i] <= 1)
break;
cout << i << ' '<< m - i << endl;
flag = true;
break;
}
}
if(flag == false){
cout << "No Solution";
}
return 0;
}