寻找指定数组元素和

题目要求:
输入正整数𝑛(𝑛≤106),𝑆(𝑆≤2×109)和𝑛个正整数ai(ai≤109)。
试判断是否存在𝑖,𝑗使得ai+aj=S。
样例输入5 7
3 6 7 2 1
样例输出 YES
样例解释 𝑎2+𝑎5=6+1=7

主要思路:
先把输入的n个数输入到数组中,然后采用双重遍历,找出两个数和为S。并且为了不重复选择,第二个遍历从第一个遍历的右边开始。结果如下:
在这里插入图片描述

#include<iostream>
#include<stdio.h>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <map>
#include <ctime>
#include <cmath>
using namespace std;
int s,t;
int select(int aa[],int nn,int SS)
{
	
	for(s=0;s<nn-1;s++)
	{
		for(t=s+1;t<nn;t++)
		{
			if(aa[s]+aa[t]==SS)
				return 1;
			
		}
	}
}

void main()
{
    int n,S;
    cout <<"输入两个正整数n、S:"<< endl;
    cin>>n>>S;
	int a[200];
	int i;
    cout<<"输入n个正整数:"<<endl;
	for(i=0;i<n;i++)
	{	cin>>a[i];
	}
	if(select(a,n,S)>0)
		cout<<"存在"<<a[s]<<"和"<<a[t]<<"的和为"<<S<<endl;
	else
		cout<<"不存在"<<endl;
    /*for(j=0;j<n;j++)
	{	cout<<a[j];
	}*/

  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值