View Code of Problem 133

//普通暴力解法时间复杂度为O(n^2),所以使用快速排序优化 
#include<stdio.h>
#include<stdlib.h>      //原来有现成的快速排序函数^_^ ,比传统的快速排序快,我写的提交会Time Limit Exceeded 
int compare(const void *a,const void *b)
{
	return *(int*)a-*(int*)b;                      //(int *)a表示将a地址强制类型转换成整形地址类型
	                                                //*(int*)a 就是得到目标地址的值
}

/*void quicksort(int R[],int low,int high){    //快速排序 
	int temp;
	int i=low,j=high;
	if(low<high){
		temp=R[low];
		while(i<j){
			while(j>i&&R[j]>=temp)
			j--;
			if(i<j){
				R[i]=R[j];
				i++;
			}
			while(i<j&&R[i]<temp)
			i++;
			if(i<j){
				R[j]=R[i];
				j--;
			}
		}
	    R[i]=temp; 
	    quicksort(R,low,i-1);
	    quicksort(R,i+1,high);
	}
} */
int main(){
     int T;
     int n,X; 
     int a[100000];
	 scanf("%d",&T);
	 while(T--){
	 	  scanf("%d %d",&n,&X); 
	 	  for(int i=0;i<n;i++)
	         scanf("%d",&a[i]);
	         
	       qsort(a,n,sizeof(int),compare);         //参数一 – 指向要排序的数组的第一个元素的指针。
		                                           //参数二 – 由 base 指向的数组中元素的个数。
		                                           //参数三– 数组中每个元素的大小,以字节为单位。
		                                           //参数四 – 用来比较两个元素的函数
	      //quicksort(a,0,n-1);           //先把数组排序一下
		  int  index1=0,index2=n-1;
		  while(index1<index2){
		  	if(a[index1]+a[index2]==X&&index1<index2){    
			  	printf("YES\n");
				break; 
			  }
			else if(a[index1]+a[index2]<X&&index1<index2)   
			    index1++;
			else 
			    index2--; 
		  }
		  if(index1==index2)
		  	printf("NO\n");
		  }
	}  

Double click to view unformatted code.


Back to problem 133