[Programming question] enter an array and a number that have been sorted in ascending order and search for two numbers in the array so that the sum of them is exactly the number entered.

Source: Internet
Author: User

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 ;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.