题意:给你一个数n和x( n < 1000000 ),再给你n个数,现在问你是否这n个数中是否能找出两个数它们的和等于x;
解析:two pointers求解;
快排+二分会TLE;
// Sum.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algorithm> #include<cstdio> #include<set> using namespace std; const int maxn = 1000005; int num1[ maxn ], num[ maxn ]; int main(){ int n, x; while( cin >> n >> x ){ for( int i = 0; i < n; ++i ){ cin >> num[ i ]; } sort( num, num + n ); bool flag = false; int i = 0, j = n - 1; while( i < n ){ while( num[ i ] + num[ j ] > x && j > 0 ){ j--; } if( num[ i ] + num[ j ] == x ){ flag = true; break; } i++; } if( flag ){ puts( "YES" ); } else{ puts( "NO" ); } } return 0; }
Sum( two pointers ),布布扣,bubuko.com
原文:http://blog.csdn.net/bo_jwolf/article/details/19994453