18. 4Sum

来源:互联网 发布:002型航母 知乎 编辑:程序博客网 时间:2024/06/07 06:07

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]]

在3Sum的基础上,在外层再添加一层循环。

public List<List<Integer>> fourSum(int[] num, int target) {        Arrays.sort(num);        ArrayList<List<Integer>> ans = new ArrayList<>();        if(num.length == 0 || 4 * num[0] > target || 4 * num[num.length - 1] < target) {            return ans;        }        for(int i = 0; i < num.length - 3; i++) {            if(i > 0 && num[i] == num[i - 1]) continue;            for(int j = i+1; j < num.length - 2; j++) {                if(j > i + 1 && num[j] == num[j-1]) continue;                int low = j + 1;                int high = num.length - 1;                while(low < high) {                    int sum = num[i] + num[j] + num[low] + num[high];                    if(sum == target){                        ans.add(Arrays.asList(num[i], num[j], num[low], num[high]));                        low++;                        high--;                        while(low < high && num[low] == num[low-1]) low++;                        while(low < high && num[high] == num[high+1]) high--;                    }                    else if(sum<target) {                        low++;                    }                    else {                        high--;                    }                }            }        }        return ans;    }
原创粉丝点击