pat甲级 A1048 Find Coins (25分)

题目链接:

https://pintia.cn/problem-sets/994805342720868352/problems/994805432256675840

 

题目分析:

1,two pointers

本题可先将该序列进行排序,然后,设置两个分别指向第一个和最后一个的下标i,j;

若有c[i] + c[j] == m,则输出c[i]、c[j],若c[i] + c[j]  < m,则将i++,若c[i] + c[j]  > m,则将j--。

2,hash()

hashtable[i]表示数字i出现的次数。若hashtable[i]和hashtable[m-i]同时大于0,则说明有数对i和m-i满足题意。注意的是,若i == m - i,则需要hashtable[i]大于1。

参考代码:

two pointer:

#include <bits/stdc++.h>
using namespace std;
int c[100010], n, m;
int main(){
    scanf("%d %d",&n, &m);
    for(int i = 0; i < n; i++){
        scanf("%d",&c[i]);
    }
    sort(c, c + n);
    int i = 0, j = n - 1;
    for(; i < j; ){
        if(c[i] + c[j]==m) {
            printf("%d %d\n",c[i], c[j]);
            break;
        }else if(c[i] + c[j] > m){
            j--;
        }else{
            i++;
        }
    }
    if(i==j) printf("No Solution\n");
    return 0;
}

 hash:

#include <bits/stdc++.h>
using namespace std;
int hashtable[1010];
int main(){
    int n, m, a;
    cin >> n >> m;
    for(int i = 0; i < n; i++){
        cin >> a;
        hashtable[a]++;
    }
    bool flag = false;
    for(int i = 1; i <= m/2; i++){
        if(hashtable[i] && hashtable[m-i]){
            if(m - i== i && hashtable[i] <= 1)
                break;
            cout << i << ' '<< m - i << endl;
            flag = true;
            break;
        }
    }
    if(flag == false){
        cout << "No Solution";
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值