4Sum

来源:互联网 发布:唯一视觉婚纱摄影 知乎 编辑:程序博客网 时间:2024/06/18 17:31

原题:

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]]
即从给定数组找出和为target的所有情况且不能重复。
思考过程&解题思路:
依旧是双指针算法,在3Sum上嵌套一层循环。
结果代码:
public List<List<Integer>> fourSum(int[] nums, int target) {    Arrays.sort(nums);    List<List<Integer>> res = new ArrayList<>();    for (int i = 0;i < nums.length;i++){        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 l = j + 1,r = nums.length - 1;            while (l < r){                if ((l > j + 1) && (nums[l] == nums[l - 1])) {                    l++;continue;                }                if ((r < nums.length - 1) && (nums[r] == nums[r + 1])) {                    r--;continue;                }                int sum = nums[l] + nums[r] + nums[i] + nums[j];                if (sum > target) r--;                if (sum < target) l++;                if (sum == target){                    List<Integer> integers = new ArrayList<>();                    integers.add(nums[i]);                    integers.add(nums[j]);                    integers.add(nums[l]);                    integers.add(nums[r]);                    res.add(integers);                    r--;l++;                }            }        }    }return res;}
原创粉丝点击