Find a pair of elements from an array whose sum equals a given number?
Some notes about the solution :
package com.mindclues.Array;; /** * * @author Mindclues */ import java.util.HashMap; import java.util.Map; public class ArrayPairSum { public static void main(String[] args) { int[] a = {2, 45, 7, 3, 5, 1, 8, 9}; printSumPairs(a, 10); } public static void printSumPairs(int[] input, int k) { Mappairs = new HashMap (); for (int i = 0; i < input.length; i++) { if (pairs.containsKey(input[i])) { System.out.println(input[i] + ", " + pairs.get(input[i])); } else { pairs.put(k - input[i], input[i]); } } } }
Output- 3, 7 8, 2 9, 1
post a comment