
Sample Input 1:
8 15
1 2 8 7 2 4 11 15
Sample Output 1:
4 11
Sample Input 2:
7 14
1 8 7 2 4 11 15
Sample Output 2:
No Solution
题解:
1.此题直接两个数两个数遍历会超时
2.设定一个cnt[]数组,下标表示数的大小,其值表示为该数出现的次数
3.i从0开始遍历,跳过cnt[i]==0的数,记t=m-i,若cnt[t] >=1 找到匹配,输出结果
代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n,m;
vector<int> ans;
int cnt[1010]= {0};
int main(){
cin >> n >> m;
int t;
for(int i=0;i<n;i++){
scanf_s("%d",&t);
cnt[t]++;
}
bool sign = true;
for(int i=0;i<1010 && sign;i++){
if(i > m) break;
else if(cnt[i] == 0){
continue;
}
else{
cnt[i]--;
t = m - i;
if(cnt[t] >= 1){
sign = false;
cout << i << " " << t;
}
cnt[i]++;
}
}
if(sign == true){
cout << "No Solution";
}
system("pause");
return 0;
}
本文介绍了一种高效算法,用于解决给定两个数字集合中寻找配对的问题,避免了传统双层遍历的超时风险。通过使用计数数组记录每个数的出现次数,仅需一次遍历即可确定是否存在匹配的对,显著提高了处理速度。
2万+

被折叠的 条评论
为什么被折叠?



