题目:输入一个已经按升序排序过的数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字。要求时间复杂度是O(n)。如果有多对数字的和等于输入的数字,输出任意一对即可。
例如输入数组1、2、4、7、11、15和数字15。由于4+11=15,因此输出4和11。
题目简单些,由于是排好序的,可以由两端出发,判断其和与指定数字的大小关系:大了则把较大的变小些,小了则把较小的变大些,相等则符合要求。
1 #include<stdio.h> 2 void getTwo(int a[],int length,int sum){ 3 if(length < 2) 4 return ; 5 if(a[0] > sum) 6 return ; 7 int i,j; 8 for(i = 0,j = length - 1; i < j;){ 9 if(a[i] + a[j] < sum) 10 i++; 11 else 12 if(a[i] + a[j] > sum) 13 j--; 14 else { 15 printf("No.%d(%d) + No.%d(%d) =%d ",i,a[i],j,a[j],sum); 16 break; 17 } 18 } 19 if(i >= j) 20 printf("No Result "); 21 } 22 int main(){//Test 23 int a[] ={1,4,8,9,10}; 24 int sum = 14; 25 getTwo(a,5,sum); 26 return 0; 27 } 28