forked from CodeSadhu/Hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SumOfTripletIsZero.java
64 lines (48 loc) · 1.09 KB
/
SumOfTripletIsZero.java
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
import java.util.*;
public class SumOfTripletIsZero {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Program using two pointer algorithm
System.out.println("Enter the size of the array:");
int n = sc.nextInt();
int[] a = new int[n];
System.out.println("Enter the elements in the array:");
for(int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
Triplet g = new Triplet();
if(g.findTriplets(a, n)) {
System.out.println("1");
}
else {
System.out.println("0");
}
sc.close();
}
}
class Triplet {
//Function to check if triplet is present
//arr[]: input array
//n: size of the array
public boolean findTriplets(int arr[], int n) {
Arrays.sort(arr);
for(int i = 0; i < n-2; i++) {
if(twoSum(arr, -arr[i], i+1)) return true;
}
return false;
}
public boolean twoSum(int a[], int x, int i) {
int j = a.length-1;
while (i < j) {
if(a[i] + a[j] > x) {
j--;
} else {
if(a[i] + a[j] < x) {
i++;
} else {
return true;
}
}
}
return false;
}
}