In this code example, the findPairs
method takes an integer array arr
and an integer target
as input and returns a list of pairs (Pair
class) containing the elements that sum up to the target value.
The algorithm uses two nested loops to iterate over all possible pairs of elements. The outer loop selects the first element, and the inner loop iterates over the remaining elements to find a matching pair.
For each pair of elements, the algorithm checks if their sum is equal to the target value. If a pair is found, it is added to the pairs
list.
In the main
method, an example input array arr
and target value target
are defined. The findPairs
method is called to find the pairs that sum up to the target value, and the resulting pairs are printed to the console.
import java.util.ArrayList;
import java.util.List;
public class PairSumFinder {
public static List<Pair<Integer, Integer>> findPairs(int[] arr, int target) {
List<Pair<Integer, Integer>> pairs = new ArrayList<>();
// Iterate over all possible pairs of elements
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] == target) {
pairs.add(new Pair<>(arr[i], arr[j]));
}
}
}
return pairs;
}
public static void main(String[] args) {
int[] arr = {2, 4, 5, 3, 6, 8};
int target = 9;
List<Pair<Integer, Integer>> result = findPairs(arr, target);
System.out.println("Pairs that sum up to " + target + " are:");
for (Pair<Integer, Integer> pair : result) {
System.out.println("(" + pair.getKey() + ", " + pair.getValue() + ")");
}
}
// Custom Pair class to hold pair of values
static class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
}