11package com .rampatra .arrays ;
22
3- /**
4- * Created by IntelliJ IDEA.
5- *
6- * @author: ramswaroop
7- * @date: 5/18/15
8- * @time: 10:24 PM
9- */
10-
113import java .util .Arrays ;
12- import java .util .HashMap ;
13- import java .util .Map ;
4+ import java .util .HashSet ;
5+ import java .util .Set ;
146
157/**
168 * Given an array ar[] of n numbers and
179 * another number x, determine whether or not there
1810 * exists two elements in ar[] whose sum is exactly x.
11+ *
12+ * @author rampatra
13+ * @since 5/18/15
1914 */
2015public class PairSum {
2116
@@ -25,18 +20,18 @@ public class PairSum {
2520 * then O(n^2) in worst case.
2621 *
2722 * @param ar
28- * @param x
23+ * @param sum
2924 * @return
3025 */
31- static boolean pairSum (int ar [] , int x ) {
26+ static boolean pairSum (int [] ar , int sum ) {
3227 Arrays .sort (ar );
3328
3429 int len = ar .length ;
3530
3631 for (int i = 0 , j = len - 1 ; i < j ; ) {
37- if (ar [i ] + ar [j ] == x ) {
32+ if (ar [i ] + ar [j ] == sum ) {
3833 return true ;
39- } else if (ar [i ] + ar [j ] < x ) { // approach towards larger elements
34+ } else if (ar [i ] + ar [j ] < sum ) { // approach towards larger elements
4035 i ++;
4136 } else { // approach towards smaller elements
4237 j --;
@@ -46,25 +41,30 @@ static boolean pairSum(int ar[], int x) {
4641 }
4742
4843 /**
49- * Using hashmap in O(n) time
44+ * Using hashmap in O(n) time.
5045 *
5146 * @param ar
52- * @param x
53- * @param map
47+ * @param sum
48+ * @param numSet
5449 * @return
5550 */
56- static boolean pairSum (int ar [] , int x , Map <Integer , Integer > map ) {
51+ static boolean pairSum (int [] ar , int sum , Set <Integer > numSet ) {
5752 for (int i = 0 ; i < ar .length ; i ++) {
58- if (map . containsKey ( x - ar [i ])) {
53+ if (numSet . contains ( sum - ar [i ])) {
5954 return true ;
6055 }
61- map . put (ar [i ], 1 );
56+ numSet . add (ar [i ]);
6257 }
6358 return false ;
6459 }
6560
6661 public static void main (String a []) {
6762 System .out .println (pairSum (new int []{-3 , 4 , -6 , 1 , 1 }, -2 ));
68- System .out .println (pairSum (new int []{-3 , 4 , -6 , 1 , 1 }, -2 , new HashMap <Integer , Integer >()));
63+ System .out .println (pairSum (new int []{-3 , 4 , -6 , 1 , 1 }, 5 ));
64+ System .out .println (pairSum (new int []{-3 , 4 , -6 , 1 , 1 }, 0 ));
65+ System .out .println ("--------" );
66+ System .out .println (pairSum (new int []{-3 , 4 , -6 , 1 , 1 }, -2 , new HashSet <>()));
67+ System .out .println (pairSum (new int []{-3 , 4 , -6 , 1 , 1 }, 5 , new HashSet <>()));
68+ System .out .println (pairSum (new int []{-3 , 4 , -6 , 1 , 1 }, 0 , new HashSet <>()));
6969 }
7070}
0 commit comments