-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtripletsum.java
More file actions
111 lines (69 loc) · 2.47 KB
/
Copy pathtripletsum.java
File metadata and controls
111 lines (69 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package arrays;
import java.util.Arrays;
import java.util.Scanner;
public class tripletsum {
public static void tripletfun(int arr[], int n, int x) {
Arrays.sort(arr);
for (int i = 0; i < n; i++) {
int start = i + 1;
int end = arr.length - 1;
int val = x - arr[i];
while (start < end) {
if (arr[start] + arr[end] < val) {
start++;
} else if (arr[start] + arr[end] > val) {
end--;
} else {
int cstart = 0, cend = 0;
for (int p = start; p <= end; p++) {
if (arr[p] == arr[start]) {
cstart++;
} else {
break;
}
}
for (int p = end; p >= start; p--) {
if (arr[p] == arr[end]) {
cend++;
} else {
break; /// for contnuous duplicates..
}
}
int pairs = cstart * cend;
if (arr[start] == arr[end]) {
pairs = ((end - start + 1) * (end - start)) / 2;
}
// print all triplet pairs.taking duplicates into account..
for (int k = 0; k < pairs; k++) {
System.out.println(arr[i] + " " + arr[start] + " " + arr[end]);
}
end -= cend;
start -= cstart;
}
}
}
}
public static void tripletfun2(int[] input, int x) {
Arrays.sort(input);
for (int i = 0; i < input.length; i++) {
for (int j = i + 1; j < input.length; j++) {
for (int k = j + 1; k < input.length; k++) {
if (input[i] + input[j] + input[k] == x) {
System.out.println(input[i] + " " + input[j] + " " + input[k]);
}
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int x;
x = sc.nextInt();
tripletfun(arr, n, x);
}
}