leetcode 018 4sum java

问题:
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:
The solution set must not contain duplicate quadruplets.
Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

解答

public List<List<Integer>> fourSum(int[] nums, int target) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    List<Integer> sub = new ArrayList<Integer>();

    HashSet<List<Integer>> set = new HashSet<List<Integer>>();
    int len = nums.length;
    Arrays.sort(nums);
    //i和j是表示第一个数和第二个数,确定第一二个数,然后寻找第3 4 个数
    for(int i = 0; i < len - 3; i ++) {
        for(int j = i + 1; j < len - 2; j ++) {
            int start = j + 1;
            int end = len - 1;
            while (start < end) {
                if(nums[i] + nums[j] + nums[start] + nums[end] == target) {
                    sub.add(nums[i]);
                    sub.add(nums[j]);
                    sub.add(nums[start]);
                    sub.add(nums[end]);
                    if(!set.contains(sub)) {
                        set.add(sub);
                        result.add(new ArrayList<Integer>(sub));
                    }
                    sub.clear();
                    start ++;
                    end --;
                }else if (target > nums[i] + nums[j] + nums[start] + nums[end]) {
                    start ++;
                }else {
                    end --;
                }
            }
        }
    }
    return result;
}