翻硬币:哈希查找+双指针

翻硬币

解法一:hash查找

数据范围是 1e5所以复杂度控制在nlogn范围之内
可以使用 h a s h hash hash查找,查找的复杂度是 O 1 O1 O1,遍历的复杂度是 O ( n ) O(n) O(n),所以综合复杂度是 O ( n ) O(n) O(n)

#include <iostream>
#include <cstring>
#include <unordered_set>
#include <algorithm>
using namespace std;

const int INF=10000;
int n,m,r;
int main()
{
    cin>>n>>m;
    int v1 = INF,v2=0;
    unordered_set<int> hash;
    for(int i=0;i<n;i++)
    {
        int a,b;
        cin>>a;
        b=m-a;
        if(hash.count(b))
        {
            hash.insert(a);
            if(a>b) swap(a,b);
            if(a<v1) v1=a,v2=b;
        }
        else hash.insert(a);
    
    }
    

    if(v1==INF)cout<<"No Solution"<<endl;
    else cout<<v1<<' '<<v2<<endl;
    return 0;
}

解法二:双指针

使用范围是:当i增大的时候j不断减小

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
const int N=100100;
int m,n;
int w[N];

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)scanf("%d",&w[i]);
    sort(w,w+n);
    for(int i=0,j=n-1;i<j;i++)
    {
        while(i<j && w[i]+w[j]>m)j--;
        if(i<j && w[i]+w[j]==m)
        {
            printf("%d %d\n",w[i],w[j]);
            return 0;
        }
    }
    puts("No Solution");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shirandexiaowo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值