Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class ThreeSum {
- public static int threeSumCubic(int[] arr) {
- int count = 0;
- for (int i=0; i<arr.length; i++) {
- for (int j=i+1; j<arr.length; j++) {
- for (int k=j+1; k<arr.length; k++) {
- if (arr[i] + arr[j] + arr[k] == 0) {
- count++;
- }
- }
- }
- }
- return count;
- }
- public static int threeSumQuadratic(int[] arr) {
- Arrays.sort(arr);
- int count = 0;
- for (int i=0; i<arr.length-2; i++) {
- int j = i+1;
- int k = arr.length-1;
- while (j < k) {
- int sum = arr[i] + arr[j] + arr[k];
- if (sum < 0) {
- j++;
- } else if (sum > 0) {
- k--;
- } else {
- count++;
- j++;
- k--;
- }
- }
- }
- return count;
- }
- public static void main(String[] args) {
- int[] arr = new int[]{0, 0, 0, 0};
- System.out.println(threeSumQuadratic(arr));
- System.out.println(threeSumCubic(arr));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement