.
/*
* 3-SUM problem
* Are there 3 numbers a, b, c among N numbers whose sum is ZERO?
* */
public class test{
public static void main(String[] args) {
int[] al = {1, 5, 7, 0, -1, -5, -8, 2, 4};
if(is3sum(al))
System.out.println("Above three numbers in the array have sum ZERO!");
else
System.out.println("There are no three numbers whose sum is ZERO");
}
static boolean is3sum(int[] al){
int j, k = 0;
int iterations = 0;
for (int i = 0; i <= al.length - 2; i++) {
j = i + 1;
k = al.length - 1;
while(k > j){
iterations++;
if(al[i] + al[j] + al[k] == 0){
System.out.println("Iterations: " + iterations);
System.out.print("Numbers: ");
System.out.println(al[i] + ", " + al[j] + ", " + al[k]);
return true;
}else if (al[i] + al[j] + al[k] > 0){
k = k - 1;
}else {
j = j + 1;
}
}
}
return false;
}
}
/*
* 3-SUM problem
* Are there 3 numbers a, b, c among N numbers whose sum is ZERO?
* */
public class test{
public static void main(String[] args) {
int[] al = {1, 5, 7, 0, -1, -5, -8, 2, 4};
if(is3sum(al))
System.out.println("Above three numbers in the array have sum ZERO!");
else
System.out.println("There are no three numbers whose sum is ZERO");
}
static boolean is3sum(int[] al){
int j, k = 0;
int iterations = 0;
for (int i = 0; i <= al.length - 2; i++) {
j = i + 1;
k = al.length - 1;
while(k > j){
iterations++;
if(al[i] + al[j] + al[k] == 0){
System.out.println("Iterations: " + iterations);
System.out.print("Numbers: ");
System.out.println(al[i] + ", " + al[j] + ", " + al[k]);
return true;
}else if (al[i] + al[j] + al[k] > 0){
k = k - 1;
}else {
j = j + 1;
}
}
}
return false;
}
}