Java code to find two elements of list whose sum equals the target

Here’s a Java code that returns the zero-based indices of any two distinct elements of list whose sum equals a given values, or returns null if no result is found.
For example, if the list is { 1, 2, 3, 5} and the target is 7, the program returns
1, 3 (2 + 5 = 7)

[cc lang=java]
import java.util.HashMap;

public class TwoSum {
public static int[] findTwoSum(int[] list, int sum) {
HashMap map = new HashMap();
int[] result = new int[2];
boolean ok = false;

for (int i = 0; i < list.length; i++) { if (map.containsKey(list[i])) { int index = map.get(list[i]); result[0] = index ; result[1] = i; ok = true; break; } else { map.put(sum - list[i], i); } } if (ok == false) { result = null; } return result; } public static void main(String[] args) { int[] indices = findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 12); System.out.println(indices[0] + " " + indices[1]); } } [/cc]

Leave a Reply

Your email address will not be published. Required fields are marked *