题目链接: https://www.acwing.com/problem/content/description/1534/
方法一:暴力(能过13/15个数据)
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100010;
int n,m;
int a[N];
int main()
{
cin>>n>>m;
for(int i = 0;i<n;i++) cin>>a[i];
sort(a,a+n);
for(int i = 0;i<n;i++)
for(int j = i + 1;j<n;j++)
{
if(a[i] + a[j] == m)
{
cout<<a[i]<<' '<<a[j]<<endl;
return 0;
}
}
cout<<"No Solution"<<endl;
return 0;
}
方法二:双指针扫描(一前一后扫描,减少时间复杂度)
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100010;
int n,m;
int a[N];
int main()
{
cin>>n>>m;
for(int i = 0;i<n;i++) cin>>a[i];
sort(a,a+n);
for(int i = 0;i<n;)
for(int j = n-1;j > i;)
{
if(i < j)
{
if(a[i] + a[j] > m) j--;
if(a[i] + a[j] < m) i++;
}
if(a[i] + a[j] == m && i != j)
{
cout<<a[i]<<' '<<a[j]<<endl;
return 0;
}
if(i == j)
{
cout<<"No Solution"<<endl;
return 0;
}
}
return 0;
}