The beauty of programming: quickly finding two numbers that meet the conditions

Source: Internet
Author: User

Can we quickly find two numbers in an array so that the sum of these two numbers is equal to a given value? To simplify the process, we assume that there must be at least one set of compliant solutions in this array.

Method 1:

The most direct method is the exhaustive method. The complexity is O (N ^ 2 );

 


Method 2:

Use sum to subtract a [I] And then search for sum-a [I]. If the sum is in the array, the result is a search. You can use binary search; the sorting complexity is O (nlgn), the search complexity is O (lgn), and the final complexity is O (nlgn );

, You can also use hash to search, but the space complexity increases by O (N );

 


Method 3: sort the order first, and then, I = 0, j = n-1. Check whether arr [I] + arr [j] is equal to sum. If it is less than sum, I ++; greater than sum, j --; Complexity: O (N) + O (NlgN );

 
 

for(i=0;j=n-1;i<j;)    if(arr[i]+arr[j]==sum)         return (i,j);    else if(arr[i]+arr[j]<sum)        i++;    else        j--;    return (i,j); for(i=0;j=n-1;i<j;)   if(arr[i]+arr[j]==sum)     return (i,j);   else if(arr[i]+arr[j]<sum)    i++;   else    j--;   return (i,j);

 

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.