Array lookup algorithm, array, a + b = c

subject

Given an unordered array, such as int[] arr={3, 5, 8, 9, 12, 21, 27}, list all sets that meet the criteria:

  1. A set contains two values a, b(a and B are in the array, and a is not equal to b)
  2. a+b=c,c also in the array

Reflection

  1. Sort first.
  2. Use the index of a and B to do nested loops, a main loop, B sub-loop, iterate out all combinations of a+b.
  3. Add the index of c to the subloop if
    Arr[a] + arr[b] > arr[c] continues to look to the right for possibly equal c++.
    Arr[a] + arr[b] < arr[c] means that it is impossible to have the same C on the right, direct b++, find the next a+b.
    Equality is put into the array.

summary

The main idea is to move a and b by using the principle of sorted arrays from small to large, and then look for the equal c on the right side of b.

Java Solution

package learning;
import java.util.*;
public class ArraySearcher {
    public static List<int[]> searchABC(int[] arr) {
        if (null == arr || arr.length == 0) {
            return null;
        }

        int length = arr.length;
        List<int[]> abcPair = new ArrayList<>();
        //Sort from smallest to largest first
        Arrays.sort(arr);
        //Main loop, moving the starting point of a to the right
        for (int a = 0; a < length ; a++) {
            int b = a;
            int c = a + 1;
            //Subcycle, mainly moving C to find a+b=c
            while (c < length) {  //From left to right
                if (arr[a] + arr[b] > arr[c]) {  
//Since the array is ordered, if a + b > c means that c may move c to the right
                    c++;
                } else if (arr[a] + arr[b] < arr[c]) {  
//If a + b < c, C cannot be on the right, b moves to the right
                    b++;
                } else {
                    int[] pair = {arr[a],arr[b],arr[c]};  
//Find abc and join the list
                    abcPair.add(pair);
                    c++;
                }
            }
        }
      return abcPair;
    }

    public static void main(String[] args) {
        int[] lst = {3,5,8,9,12,21,27};
        List<int[]>  result = ArraySearcher.searchABC(lst);
        for(int[] l: result) {
            System.out.println(l[0]+ " + " + l[1] + " = " + l[2]);
        }
    }

}

Tags: Java

Posted on Sat, 04 Jul 2020 10:36:57 -0400 by mpunn