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