4 Sum

Question

Given an array S of n integers, are there elements a, b, c, and d in S 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.

For example, given array S = [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] ]

Solution

这道题和2sum,3sum一样,也是用two pointers的方法。

固定第一个数,移动第二个数(第一个数后面),在第二个数之后的数之中用2sum寻找target。有几点要注意:

  1. 注意有重复的数,为了避免重复答案,只能取第一个重复的数

  2. 注意conor case,数组长度小于4不行,排序后若最小值的4倍大于targte或者最大值的4倍小于target不行

代码如下:

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(nums == null || nums.length < 4){
            return res;
        }

        Arrays.sort(nums);
        if(4 * nums[0] > target || 4 * nums[nums.length - 1] < target){
            return res;
        }

        for(int i = 0; i < nums.length - 3; i++){
            //skip duplicate
            if(i != 0 && nums[i] == nums[i - 1]){
                continue;
            }

            for(int j = i + 1; j < nums.length - 2; j++){
                if(j != i + 1 && nums[j] == nums[j - 1]){
                    continue;
                }

                int head = j + 1;
                int tail = nums.length - 1;
                while(head < tail){
                    int sum = nums[i] + nums[j] + nums[head] + nums[tail];
                    if(sum == target){
                        List<Integer> list = new ArrayList<Integer>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[head]);
                        list.add(nums[tail]);
                        res.add(list);
                        head++;
                        tail--;
                        while(head < tail && nums[head] == nums[head - 1]){
                            head++;
                        }
                        while(head < tail && nums[tail] == nums[tail + 1]){
                            tail--;
                        }
                    }else if(sum < target){
                        head++;
                    }else{
                        tail--;
                    }
                }
            }
        }
        return res;
    }
}

results matching ""

    No results matching ""