浙大pat | 牛客网甲级 1037Find Coins (25) 数组循环遍历

本文介绍了一种使用双指针技术解决特定支付问题的方法。该问题要求从给定的硬币面额中找出两个可以恰好支付指定金额的组合。通过先排序再使用双指针逼近目标和的方式,确保了算法的有效性和效率。

题目描述

Eva loves to collect coins from all over the universe, includingsome other planets like Mars.  One dayshe visited a universal shopping mall which could accept all kinds of coins aspayments.  However, there was a specialrequirement of the payment: for each bill, she could only use exactly two coinsto pay the exact amount.  Since she hasas many as 105 coins with her, she definitely needsyour help.  You are supposed to tell her,for any given amount of money, whether or not she can find two coins to pay forit.



输入描述:

Each input file contains one test case.  For each case, the first line contains 2positive numbers: N (<=105, the total number of coins) and M(<=103, the amount of money Eva has topay).  The second line contains N facevalues of the coins, which are all positive numbers no more than 500.  All the numbers in a line are separated by aspace.




输出描述:

For each test case, print in one line the two face values V1 and V2 (separated by a space) such that V1 + V2 = M and V1 <= V2. If such a solution is not unique, output the one with the smallest V1. If there is no solution, output "No Solution" instead.



输入例子:

8 15

1 2 8 7 2 4 11 15



输出例子:

4 11

这题给你一个数组,问你这个数组里面是否有两个数,相加为题目中给定的一个数

这里需要注意的一个地方就是,题目中并没有说给定的所有数都是正整数,只说了是正数,但是实际上,你在编程的时候只需要考虑给定的数都是正整数就好了,不知道这算不算是一个BUG

这一题使用解决这一类问题的传统方法,设定两个指针,分别指向排序后的数组的第一个元素和最后一个元素,如果这两个元素的和大于给定的数,将第二个指针前移,如果这两个数的和小于给定的数,则将第一个指针后移,一直到找到和为给定的数的两个数或者是前指针和后指针重合,算法结束

#include <iostream>
#include <algorithm>
using namespace std;
int coins[100003];
int main()
{
	int N,M;
	int pointOne,pointTwo;
	cin>>N>>M;
	for(int i=0;i<N;i++)
		cin>>coins[i];
	sort(coins,coins+N);
	pointOne = 0;
	pointTwo = N-1;

	while(1)
	{
			while(pointOne < pointTwo && coins[pointOne] + coins[pointTwo] <M) pointOne++;
			if(pointOne == pointTwo || coins[pointOne] + coins[pointTwo] == M) break;
			while(pointOne < pointTwo && coins[pointOne] + coins[pointTwo] >M) pointTwo--;
			if(pointOne == pointTwo || coins[pointOne] + coins[pointTwo] == M) break;
	}
	if(pointTwo == pointOne) cout<<"No Solution";
	else
	{
		cout<<coins[pointOne]<<" "<<coins[pointTwo];
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值