Description
This is an interview question from an Internet company. The input is an array sorted in ascending order and a number n. You must search for two numbers in the array, so that their sum is exactly the same as the input number n. If there are multiple pairs of numbers and the sum is equal to N, output any one.
The simple solution uses two variables, I and j, and uses two loops to traverse the array. When data [I] + data [J] is equal to the input number and I is not equal to J, output Data [I] AND DATA [J], that is, find the two numbers you want. The code for this solution is as follows:
void find1(int *data,int num){assert(NULL!=data);int i=0;int j=0;for(i=0;i<len;i++)for(j=0;j<len;j++){if((i!=j)&&((data[i]+data[j])==num)){printf(" %d + %d = %d \n",data[i],data[j],num);return;}}printf(" not find them \n");return;}
It is easy to see that the time complexity of this solution is O (n ^ 2), and the ascending array condition is not fully utilized. For a more rational solution, we can use two variables to find the first and last elements of the array, that is, the minimum and maximum values of the array. If the sum of the two numbers is equal to the input number N, the result is displayed. If the sum of the two numbers is less than N, move to the right to point to the variable with a smaller value. If the sum of the two numbers is greater than N, move to the left to point to the variable with a larger value. The condition for determining the end is that the two variables overlap.
The code for this solution is as follows:
void find2(int *data,int num){assert(NULL!=data);int i=0;int j=len-1;while(i<j){if((data[i]+data[j])==num){printf(" %d + %d = %d \n",data[i],data[j],num);return;}else if((data[i]+data[j])< num){i++;}else{j--;}}printf(" not find them \n");return;}
Obviously, the time complexity of the second solution is O (n), which is better than the first solution and can fully utilize the ascending array conditions in the question.