The problem statement from leetcode says:
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Fin
public class FourSum {
private static int countFourSum(int[] numbers) {
int count = 0;
for (int j = 0; j < numbers.length; j++) {
for (int i = j + 1; i < numbers.length; i++) {
int front = i + 1, rear = numbers.length - 1;
while (front < rear) {
if (numbers[front] + numbers[rear] + numbers[i] + numbers[j] == 0) {
System.out.printf(String.format("{%d} : {%d} : {%d} : {%d} \n", numbers[front], numbers[rear],
numbers[j], numbers[i]));
front++;
rear--;
count++;
} else {
if (Math.abs(numbers[front]) > Math.abs(numbers[rear])) {
front++;
} else {
rear--;
}
}
}
}
}
return count;
}
public static void main(String[] args) {
int[] numbers = { 1, 2, 3, 4, -4, -5, -6, 2, 4, -1 };
Arrays.sort(numbers);
System.out.println(countFourSum(numbers));
}
}