File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .*;
2+ import java .lang .*;
3+ import java .io .*;
4+
5+ class TwoPointersAlgo {
6+ //This function prints all pairs in the array that sum to a number X. If no such pair exists then output will be -1.
7+ static void twoSum (int A [], int X )
8+ {
9+ Arrays .sort (A );
10+
11+ //Array sorting is necessary for this algo to function correctly
12+
13+ int n = A .length ;
14+ int i = 0 , j = n -1 , flag =0 ;
15+ //Implementation of the algorithm starts
16+ while (i <j )
17+ {
18+ if (A [i ]+A [j ]==X )
19+ {
20+ System .out .println (A [i ] + " " + A [j ] + " " + X );
21+ flag = 1 ;
22+ i ++;
23+ j --;
24+ }
25+ else if (A [i ]+A [j ]<X )
26+ {
27+ i ++;
28+ }
29+ else j --;
30+ }
31+
32+ //Implementation ends
33+
34+ if (flag ==0 )
35+ System .out .println (-1 );
36+ }//end of function twoSum
37+ public static void main (String [] args ) {
38+ Scanner in = new Scanner (System .in );
39+ int t ,n ;
40+ t = in .nextInt ();
41+ //for number of test cases
42+ while (t >0 )
43+ {
44+ t --;
45+ n = in .nextInt ();
46+ int a [] = new int [n ];
47+ for (int i = 0 ; i <n ; i ++)
48+ {
49+ a [i ] = in .nextInt ();
50+ }
51+ //taking array input
52+ int k = in .nextInt (); //the total of the pair entered by the user
53+ twoSum (a , k );
54+
55+ }
56+ }//end of main
57+ }//end of class
58+
59+ /*Sample Input/Output
60+ Input:
61+ 2
62+ 7
63+ 1 2 3 4 5 6 7
64+ 98
65+ 7
66+ 1 2 3 4 5 6 7
67+ 8
68+ Output:
69+ -1
70+ 1 7 8
71+ 2 6 8
72+ 3 5 8
73+ */
You can’t perform that action at this time.
0 commit comments