Initialize a HashSet to store the elements we encounter.
Iterate through the array and for each element, calculate the complement that would sum to the target value.
Check if the complement exists in the HashSet. If it does, print the pair.
Add the current element to the HashSet.
Code Example:
import java.util.*;
public class Main {
public static void findPairs(int[] array, int sum) {
// Create a HashSet to store elements
HashSet<Integer> seen = new HashSet<>();
System.out.println("Pairs with sum " + sum + ":");
// Iterate through each element in the array
for (int num : array) {
// Calculate the complement
int complement = sum - num;
// Check if the complement is in the HashSet
if (seen.contains(complement)) {
System.out.println("(" + complement + ", " + num + ")");
}
// Add the current element to the HashSet
seen.add(num);
}
}
public static void main(String[] args) {
int[] array = {1, 4, 5, 7, 3, 9, 2, 10, 0};
int sum = 10;
findPairs(array, sum);
}
}
Output,
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Here's a step-by-step implementation in Java:
Code Example:
Output,