题目描述
伊娃喜欢从整个宇宙中收集硬币。
有一天,她去了一家宇宙购物中心购物,结账时可以使用各种硬币付款。
但是,有一个特殊的付款要求:每张帐单,她只能使用恰好两个硬币来准确的支付消费金额。
给定她拥有的所有硬币的面额,请你帮她确定对于给定的金额,她是否可以找到两个硬币来支付。
输入格式
第一行包含两个整数 N 和 M,分别表示硬币数量以及需要支付的金额。
第二行包含 N 个整数,表示每个硬币的面额。
输出格式
输出一行,包含两个整数 V1,V2,表示所选的两个硬币的面额,使得 V1≤V2 并且 V1+V2=M。
如果答案不唯一,则输出 V1最小的解。
如果无解,则输出 No Solution。
数据范围
1≤N≤10,
1≤M≤1000
输入样例
8 15
1 2 8 7 2 4 11 15
输出样例
4 11
这道题我用了三道方法做,分别是哈希表,双指针和暴力枚举。
哈希表
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m,x,y,temp,v1=1e5,v2;
set<int> mp;
cin>>n>>m;
while(n--){
cin>>x;
y=m-x;
if(mp.count(y)){
if(x>y){
temp=x;
x=y;
y=temp;
}
if(x<v1){
v1=x;
v2=y;
}
}
else{
mp.insert(x);
}
}
if(v1<1e5)
cout<<v1<<" "<<v2;
else
cout<<"No Solution";
return 0;
}
双指针
#include<iostream>
#include<map>
#include<bits/stdc++.h>
const int N=1e5+10;
using namespace std;
int str[N];
int main(){
int n,m,sum,i,j;
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>str[i];
}
sort(str,str+n);
i=0;
j=n-1;
while(i<j){
if(str[i]+str[j]==m){
cout<<str[i]<<" "<<str[j];
return 0;
}
if(str[i]+str[j]<m)
i++;
else
j--;
}
cout<<"No Solution";
return 0;
}
暴力枚举
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int main(){
int n,m,sum;
int str[N];
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>str[i];
}
sort(str,str+n);
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
sum=str[i]+str[j];
if(sum==m){
cout<<str[i]<<" "<<str[j];
return 0;
}
}
}
cout<<"No Solution";
return 0;
}
暴力枚举这种方法时间复杂度较高,最重要的是提交时会超时,所以不建议使用。