4sum implementation in Java from leetcode

前端 未结 6 757
生来不讨喜
生来不讨喜 2021-01-07 11:50

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

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-07 12:12

    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));
    }
    

    }

提交回复
热议问题