[C++] PAT 1048 Find Coins (25分)

本文介绍了一种高效算法,用于解决给定两个数字集合中寻找配对的问题,避免了传统双层遍历的超时风险。通过使用计数数组记录每个数的出现次数,仅需一次遍历即可确定是否存在匹配的对,显著提高了处理速度。

在这里插入图片描述

Sample Input 1:

8 15
1 2 8 7 2 4 11 15

Sample Output 1:

4 11

Sample Input 2:

7 14
1 8 7 2 4 11 15

Sample Output 2:

No Solution

题解:

1.此题直接两个数两个数遍历会超时
2.设定一个cnt[]数组,下标表示数的大小,其值表示为该数出现的次数
3.i从0开始遍历,跳过cnt[i]==0的数,记t=m-i,若cnt[t] >=1 找到匹配,输出结果

代码:
#include <iostream>
#include <vector>
#include <algorithm>


using namespace std;

int n,m;
vector<int> ans;
int cnt[1010]= {0};

int main(){
	cin >> n >> m;
	int t;
	for(int i=0;i<n;i++){
		scanf_s("%d",&t);
		cnt[t]++;
	}

	bool sign = true;

	for(int i=0;i<1010 && sign;i++){
		if(i > m) break;
		else if(cnt[i] == 0){
			continue;
		}
		else{
			cnt[i]--;
			t = m - i;
			if(cnt[t] >= 1){
				sign = false;
				cout << i << " " << t;
			}
			cnt[i]++;
		}
	}

	if(sign == true){
		cout << "No Solution"; 
	}


	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值