Find out if any two numbers in the array are added equal to a K value (assuming that there are two numbers in the array), which is an algorithm question previously asked on 36 Krypton two sides.
Idea 1: Exhaustive method, two-tier for loop
Idea 2: You can use the hash table to store the elements in the array, so we get a number, to judge that Sum-val is not in the array, if in the array, then found a pair of two tuples, their sum of sums, the disadvantage of the algorithm is that need to use a hash table, increase the complexity of space.
Idea 3: The same is based on lookup, we can first sort the array, then after a number, in the array with a binary lookup, to find out if there is a sum-val, if it exists, then found a pair of two-tuple, and their sum, compared to the above method, although not to implement a hash table, There is no need for too much space, but a lot of time. Sort needs O (NLOGN), binary lookup needs (LOGN), lookup n times, so the time complexity is O (NLOGN).
Idea 4: This method is based on the 2nd train of thought, but optimized, in time complexity and space complexity is a compromise, but the algorithm is simple and intuitive, easy to understand. First, sort the array, then use two pointers to the array, one to scan backwards, one to scan from the back, and fist + last < sum to move fist forward if fist + last > Sum, then last move backwards.
Idea 4
public static void Main (String args[]) {
int[] data = {1, 5, 9,-1, 4, 6,-2, 3,-8};
Arrays.sort (data);
PRINTPAIRSUMS1 (data, data.length, 8);
}
private static void Printpairsums (int data[], int size, int sum) {
int-i = 0;
int last = size-1;
int s = 0;
while (a < last) {
s = Data[first] + data[last];
if (s = = sum) {
System.out.println ("-------" + Data[first] + "+" + data[last] + "=" + sum);
first++;
last--;
} else if (s < sum) {
first++;
} else {
last--}
}}