AcWing 1532. 找硬币

伊娃喜欢从整个宇宙中收集硬币。

有一天,她去了一家宇宙购物中心购物,结账时可以使用各种硬币付款。

但是,有一个特殊的付款要求:每张帐单,她只能使用恰好两个硬币来准确的支付消费金额。

给定她拥有的所有硬币的面额,请你帮她确定对于给定的金额,她是否可以找到两个硬币来支付。

输入格式

第一行包含两个整数 N 和 M,分别表示硬币数量以及需要支付的金额。

第二行包含 N 个整数,表示每个硬币的面额。

输出格式

输出一行,包含两个整数 V1,V2,表示所选的两个硬币的面额,使得 V1≤V2并且 V1+V2=M。

如果答案不唯一,则输出 V1 最小的解。

如果无解,则输出 No Solution

数据范围

1≤N≤105,
1≤M≤1000

输入样例1:

8 15
1 2 8 7 2 4 11 15

输出样例1:

4 11

输入样例2:

7 14
1 8 7 2 4 11 15

输出样例2:

No Solution

 思路:和力扣的两数之和题目一样使用hash表存储所有的硬币面额,O(N)时间扫描一遍hash表,每次寻找hash[i]和hash[k-i](k为消费金额)是否存在即可.

#include<iostream>
#include<unordered_map>
using namespace std;
int n,k;
int main(){
    cin>>n>>k;
    int temp;
    int a[2]={1010,1010};
    unordered_map<int,int> hash;
    for(int i=0;i<n;i++){
        cin>>temp;
        hash[temp]++;
    }
    for(auto &i:hash){
        i.second--;
        if(hash.count(k-i.first) && hash[k-i.first]){
            if(min(k-i.first,i.first)<min(a[0],a[1])){
                a[0]=min(k-i.first,i.first);
                a[1]=max(k-i.first,i.first);
            }
        }
    }
    if(a[1]!=1010 && a[0]!=1010) cout<<a[0]<<' '<<a[1]<<endl;
    else cout<<"No Solution"<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wd2ctp88/article/details/112798085