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+ package Others ;
2+
3+ import java .util .Scanner ;
4+ import java .util .Arrays ;
5+
6+ /**
7+ * To find triplet equals to given sum in complexity O(n*log(n))
8+ *
9+ *
10+ * Array must be sorted
11+ *
12+ * @author Ujjawal Joshi
13+ * @date 2020.05.18
14+ *
15+ * Test Cases:
16+ Input:
17+ * 6 //Length of array
18+ 12 3 4 1 6 9
19+ target=24
20+ * Output:3 9 12
21+ * Explanation: There is a triplet (12, 3 and 9) present
22+ in the array whose sum is 24.
23+ *
24+ *
25+
26+ */
27+
28+
29+ class threesum {
30+ public static void main (String args [])
31+ {
32+ Scanner sc =new Scanner (System .in );
33+ int n =sc .nextInt (); //Length of an array
34+
35+ int a []=new int [n ];
36+
37+ for (int i =0 ;i <n ;i ++)
38+ {
39+ a [i ]=sc .nextInt ();
40+ }
41+ System .out .println ("Target" );
42+ int n_find =sc .nextInt ();
43+
44+ Arrays .sort (a ); // Sort the array if array is not sorted
45+
46+ for (int i =0 ;i <n ;i ++){
47+
48+ int l =i +1 ,r =n -1 ;
49+
50+ while (l <r ){
51+ if (a [i ]+a [l ]+a [r ]==n_find ) {System .out .println (a [i ]+" " + a [l ]+" " +a [r ]);break ;} //if you want all the triplets write l++;r--; insted of break;
52+ else if (a [i ]+a [l ]+a [r ]<n_find ) l ++;
53+ else r --;
54+ }
55+ }
56+
57+
58+
59+ }
60+ }
Original file line number Diff line number Diff line change 1+ package Others ;
2+
3+ import java .util .*;
4+
5+ /**
6+ * Rotation of array without using extra space
7+ *
8+ *
9+ * @author Ujjawal Joshi
10+ * @date 2020.05.18
11+ *
12+ * Test Cases:
13+
14+ Input:
15+ 2 //Size of matrix
16+ 1 2
17+ 3 4
18+ Output:
19+ 3 1
20+ 4 2
21+ ------------------------------
22+ Input:
23+ 3 //Size of matrix
24+ 1 2 3
25+ 4 5 6
26+ 7 8 9
27+ Output:
28+ 7 4 1
29+ 8 5 2
30+ 9 6 3
31+ *
32+ */
33+
34+ class main {
35+ public static void main (String [] args )
36+ {
37+ Scanner sc =new Scanner (System .in );
38+ int n =sc .nextInt ();
39+ int a [][]=new int [n ][n ];
40+
41+ for (int i =0 ;i <n ;i ++)
42+ {
43+ for (int j =0 ;j <n ;j ++)
44+ {
45+ a [i ][j ]=sc .nextInt ();
46+ }
47+ }
48+ int temp =0 ;
49+
50+ // Rotation of array by swapping their values
51+ for (int i =0 ;i <n /2 ;i ++)
52+ {
53+ for (int j =i ;j <n -i -1 ;j ++)
54+ {
55+ temp =a [i ][j ];
56+ a [i ][j ]=a [n -j -1 ][i ];
57+ a [n -j -1 ][i ]=a [n -i -1 ][n -j -1 ];
58+ a [n -i -1 ][n -j -1 ]=a [j ][n -i -1 ];
59+ a [j ][n -i -1 ]=temp ;
60+ }
61+ }
62+
63+ // printing of sorted array
64+ for (int i =0 ;i <n ;i ++){
65+ for (int j =0 ;j <n ;j ++){
66+ System .out .print (a [i ][j ]+" " );
67+
68+ }
69+ System .out .println ();
70+ }
71+
72+ }
73+
74+
75+ }
You can’t perform that action at this time.
0 commit comments