Sum 判断数组中时候有两个数的和等于一个定值 (数组很大) O(n)

这是一个关于数组的问题,给定一个包含n个数的数组和一个目标值x,需要判断数组中是否存在两个数的和等于x。程序通过排序和双指针法检查是否有符合条件的数对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sum

Time Limit: 9000 MS Memory Limit: 65536 K


Sum

Mr. Jojer is given n numbers and an extra integer x, he wants to know whether there are two numbers whose sum is x.

Input

The input file contains several test cases. The first line of each test case contains two integers, n(<=1000001) and x. From the next line of each test case, there are n numbers.

Output

Each test case corresponds to a line in the output, which is either "YES" if there exists an answer or "NO" if not.

Sample Input

3 3
1 2 3
2 3
1 3

 


Sample Output

YES
NO

 

 

 

#include<iostream>
#include<algorithm>
using namespace std;
int a[1001],n,goal;
int main()
{
 int i,j;
 while(scanf("%d%d",&n,&goal)==2)
 {
  for(i=0;i<n;i++)
  { 
   scanf("%d",&a[i]);
  }
  sort(a,a+n);
  if(a[n-4]+a[n-1]+a[n-2]+a[n-3]<goal) {printf("NO/n");continue;}
  int flag=0;
  for(i=0;i+3<n;i++)
  {
   if(a[i]+a[i+1]+a[i+2]+a[i+3]>goal) break;
  
   for(j=i+1;j<n;j++)
   {
    int low=j+1,high=n-1,t;
    while (low<high)
    {
     t=a[low]+a[high]+a[i]+a[j];
     if (t==goal) {flag=1;break;}
     else if (t<goal) low++;
     else high--;
    }
    if(flag) break;
   }
   if(flag) break;
  }
  if(flag) printf("YES/n");
  else printf("NO/n");
 }
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值