import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param nums int整型一维数组
     * @param target int整型
     * @return int整型二维数组
     */
     public int[][] fourSum(int[] nums, int target) {
        // write code here
        Arrays.sort(nums);
        int start = 0;
        LinkedList<int[]> linkedList = new LinkedList<>();
        while (start<nums.length-3) {
            if(start>=1 && nums[start]==nums[start-1]){
                start++;
                continue;
            }
            int end = nums.length-1;
            while (end >= 3) {
                if(end<=nums.length-2 && nums[end]==nums[end+1]){
                    end--;
                    continue;
                }
                int left = start + 1;
                int right = end - 1;
                while (left < right) {
                    if (nums[left] + nums[right] == target - nums[start] - nums[end]) {
                        linkedList.add(new int[]{nums[start], nums[left], nums[right], nums[end]});
                        left++;
                        right--;
                    } else if (nums[left] + nums[right] > target - nums[start] - nums[end]) {
                        right--;
                    } else if (nums[left] + nums[right] < target - nums[start] - nums[end]) {
                        left++;
                    }
                }
                end--;
            }
            start++;
        }

        int[][] arr = new int[linkedList.size()][];
        for (int i = 0; i < linkedList.size(); i++) {
            arr[i] = linkedList.get(i);
        }
        return arr;
    }
}

本题考察的知识点是双指针的应用,所用编程语言是java

我们其实这题固定一个位置,这题这就是跟上一题一样的解法了,所以我们先固定一个位置,然后就是三个数之和等于目标值。对于找数组中合适的三个数之和求目标值,我们再继续固定一个目标值,然后就是双指针之和求目标值。