File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ //In this code a array is taken along with an target element. The sum of two elements matching with the target element is displayed
2
+
3
+
4
+ import java .util .*;
5
+ public class Two_Sum {
6
+ public static void main (String args [])
7
+ {
8
+ try (Scanner sc = new Scanner (System .in )) {
9
+ int n = sc .nextInt ();
10
+ // length of the array is taken
11
+ int a [] = new int [n ];
12
+ for (int i = 0 ; i < n ; i ++)
13
+ {
14
+ a [i ] = sc .nextInt ();
15
+ }
16
+ int target =sc .nextInt ();
17
+ // target value is initialzized
18
+ int array [] = new int [2 ];
19
+ a =twoSum (array ,target );
20
+ // method is called
21
+ for (int i =0 ;i <2 ;i ++)
22
+ {
23
+ System .out .print (a [i ]+" " );
24
+ }
25
+ System .out .println ();
26
+ }
27
+ }
28
+ public static int [] twoSum (int [] n , int target ) {
29
+ Map <Integer ,Integer > nm =new HashMap <>();
30
+ // hashmap is created to store the array elements
31
+ int array []=new int [2 ];
32
+ int k =n .length ;
33
+ for (int i =0 ;i <k ;i ++)
34
+ {
35
+ if (nm .containsKey (target -n [i ]))
36
+ {
37
+ array [0 ]=nm .get (target -n [i ]);
38
+ array [1 ]=i ;
39
+ break ;
40
+ // The sum of the elements equals to the target is storee
41
+ }
42
+ nm .put (n [i ],i );
43
+ }
44
+ return array ;
45
+ // the answer array is returned
46
+ }
47
+ }
You can’t perform that action at this time.
0 commit comments