problem , enter an ascending sort array and a number s, look up two numbers in the array so that their sum is exactly s, and if there are many pairs of numbers and equals s, output any pair .
Obviously, it is very soon to think that the brute force method (O (N2)), first fixed a number, and then judge the remaining n-1 number and whether it is equal to S. This efficiency is obviously a bit low, we can use the following faster way, time complexity O (n).
idea : We start with the beginning and end of the array of two records, starting at the tail of the array, and asking for two numbers and
If the sum of two numbers is greater than the number of s that we need to require, then the subsequent record is moved forward one (because it is ordered, forward one bit, equivalent to the value reduction), and then the judgment,
If the sum of two numbers is less than the number of s required by us, then the previous position is recorded after one (because it is well-ordered, one after the other, the equivalent of an increase in value), then the judgment,
until the location is found or the back or previous position is recorded coincident.
Code Implementation :
/** * Enter an incrementing sorted array and a number s, looking for two numbers in the array so that their sum is exactly s, and if there are many pairs of numbers and equals s, output any pair. Because Java can only * have a return value, here returns the True or FALSE, or can be changed to the group, return to find the two number, where the implementation returns whether found, if found to print out! * @param data to find the incrementing array * @param length of the array * @param sum to find and * @return to find success! */public static Boolean findnumberwithsum (int data[],int length,int sum) {Boolean found = false; if (length < 1) {return found; } int ahead = Length-1; The subscript int of the larger number behind = 0; Subscript for smaller numbers while (ahead > behind) {long cursum = Data[ahead] + data[behind]; if (cursum = = sum) {System.out.println ("Find successful! Two numbers: "+data[ahead]+", "+ Data[behind"); Break } else if (Cursum > Sum) {ahead--; } else {behind + +; }} return found; }
Test:
public static void Main (string[] args) { int[] arr = {1,2,4,7,11,15}; Findsumequalnum.findnumberwithsum (arr,arr.length,15); }
Results:
Find success! Two numbers: 11,4
Find two numbers and for a certain number