View Code of Problem 133

#include<iostream> 
#include<algorithm>
using namespace std;
//二刷  二分查找的变形 
int main(){
	int T;
	scanf("%d",&T);
	while(T--) {
		int n, x;
		scanf("%d %d", &n, &x);
		int arr[n];
		for(int i=0; i<n; i++){
			scanf("%d",&arr[i]);
		}
		
		sort(arr, arr+n);  //快速排序 
		
		int flag = 0;		
		int low = 0, high = n-1;
		while(low < high) { //判断S中是否存在两个数A、B,使之和等于X。因为是要找两个数,所以传统的二分查找不行 
			if(arr[low] + arr[high] == x){
				printf("YES\n");
				flag=1;
				break; //break要放在最后 
			}
			else if(arr[low] + arr[high] < x){
				low++;
			}
			else high--;
		}
		
		if(flag==0){
			printf("NO\n");
		}
	}
	return 0;
}

Double click to view unformatted code.


Back to problem 133