14th questions (array ):
Question: enter an array and a number that have been sorted in ascending order,
Search for two numbers in the array so that their sum is exactly the number entered.
The time complexity is O (n ). If there are multiple pairs of numbers and the sum is equal to the input number, output any one.
For example, input arrays 1, 2, 4, 7, 11, 15, and numbers 15. Because 4 + 11 = 15, 4 and 11 are output.
If the time required is O (n), it must be scanned once. There are two more numbers to be searched for, so we can only find one from the beginning and one from the back to the front to set the marker to the last number, and the small value is set to the first number, if the number and sum are greater than or equal to the sum, the numeric value of the large number is reduced. Otherwise, the numeric value of the Small number is increased. Contract until the number meets or find a proper solution.
/* 14th question (array): Question: enter an array and a number that have been sorted in ascending order to search for two numbers in the array, so that the sum of them is exactly the number entered. The time complexity is O (n ). If there are multiple pairs of numbers and the sum is equal to the input number, output any one. For example, input arrays 1, 2, 4, 7, 11, 15, and numbers 15. Because 4 + 11 = 15, 4 and 11 are output. */# Include <stdio. h> int findsum (int * In, int Len, int sum) // input array length and {int I, j; for (I = 0, j = len-1; I <j;) {If (in [I] + in [J] = sum) {printf ("% d = % d + % d", sum, in [I], in [J]); return 1;} else if (in [I] + in [J] <sum) {I ++ ;} else {J -- ;}} printf ("No answer"); Return 0 ;}int main () {int A [20] = {1, 2, 4, 7, 11, 15 }; int n = 6; findsum (A, N, 15); Return 0 ;}