资讯专栏INFORMATION COLUMN

[LeetCode] 4Sum & 4Sum II

sydMobile / 3228人阅读

摘要:和方法一样,多一个数,故多一层循环。完全一致,不再赘述,

4Sum Problem

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.

Notice

Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.

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)
Note

和3Sum方法一样,多一个数,故多一层循环。完全一致,不再赘述,

Solution
public class Solution {
    public ArrayList> fourSum(int[] A, int target) {
        int n = A.length;
        ArrayList> res = new ArrayList();
        Arrays.sort(A);
        for (int i = 0; i < n-3; i++) {
            if (i != 0 && A[i] == A[i-1]) continue;
            for (int j = i+1; j <= n-3; j++) {
                if (j != i+1 && A[j] == A[j-1]) continue;
                int left = j+1, right = n-1;
                while (left < right) {
                    int sum = A[i]+A[j]+A[left]+A[right];
                    if (sum == target) {
                        ArrayList temp = new ArrayList();
                        temp.add(A[i]);
                        temp.add(A[j]);
                        temp.add(A[left]);
                        temp.add(A[right]);
                        res.add(temp);
                        left++;
                        right--;
                        while (left < right && A[left] == A[left-1]) left++;
                        while (left < right && A[right] == A[right+1]) right--;
                    }
                    else if (sum < target) left++;
                    else right--;
                }
            }
        }
        return res;
    }
}
Update 2018-10
class Solution {
    public List> fourSum(int[] nums, int target) {
        List> res = new ArrayList<>();
        if (nums == null || nums.length < 4) return res;
        Arrays.sort(nums);
        int len = nums.length;
        if (nums[0] * 4 > target || nums[len-1] * 4 < target) return res;
        for (int i = 0; i < len-3; i++) {
            if (i != 0 && nums[i] == nums[i-1]) continue;
            for (int j = i+1; j < len-2; j++) {
                if (j != i+1 && nums[j] == nums[j-1]) continue;
                int left = j+1, right = len-1;
                while (left < right) {
                    int sum = nums[i]+nums[j]+nums[left]+nums[right];
                    if (sum == target) {
                        List temp = new ArrayList<>();
                        temp.addAll(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        res.add(temp);
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left-1]) left++;
                        while (left < right && nums[right] == nums[right+1]) right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        right--;
                    }
                }
            }
        }
        return res;
    }
}
4Sum II Problem

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example:

Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

Output:
2

Explanation:
The two tuples are:

(0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0

(1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

Solution
class Solution {
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        int len = A.length;
        if (len == 0) return 0;
        Map map = new HashMap<>();
        for (int a: A) {
            for (int b: B) {
                int sum = a+b;
                map.put(sum, map.getOrDefault(sum, 0)+1);
            }
        }
        int count = 0;
        for (int c: C) {
            for (int d: D) {
                int sum = c+d;
                if (map.containsKey(-sum)) count += map.get(-sum);
            }
        }
        return count;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65951.html

相关文章

  • 【LC总结】K Sum (Two Sum I II/3Sum/4Sum/3Sum Closest)

    摘要:找符合条件的总数。双指针区间考虑边界,长度,为空,等。之后的范围用双指针和表示。若三个指针的数字之和为,加入结果数组。不要求,所以不用判断了。同理,头部两个指针向后推移,后面建立左右指针夹逼,找到四指针和为目标值的元素。 Two Sum Problem Given an array of integers, find two numbers such that they add up ...

    awesome23 评论0 收藏0
  • leetcode 18 4Sum

    摘要:题目详情输入一个长度为的整数数组和一个目标整数,我们需要找出是否存在个元素,使得的和等于。如果有,输出这样的非重复的元素序列。在求元素的时候可以通过左右指针减少查找时间。 题目详情 Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target...

    Vixb 评论0 收藏0
  • [Leetcode] Two Sum, 3Sum,4Sum,4SumII,3Sum Closet

    摘要:解题思路题目要求两个数和等于,返回其题目说明不会有重复情况,所以我们一旦发现符合情况的,就可以直接结束循环并返回。特殊情况就是正好等于,那肯定是最接近的情况,直接返回即可。 Two SumGiven an array of integers, return indices of the two numbers such that they add up to a specific ta...

    EddieChan 评论0 收藏0
  • leetcode14 4sum

    摘要:这里需要注意及时处理掉重复的情况。那么就需要尽可能排除不可能的情况来提高计算效率。因为数组已经被排序,所以可以根据数组中元素的位置判断接下来的情况是否有可能合成目标值。 题目要求 此处为原题地址 Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d =...

    MoAir 评论0 收藏0
  • [Leetcode] 3Sum 4Sum 3Sum Closet 多数和

    摘要:为了避免得到重复结果,我们不仅要跳过重复元素,而且要保证找的范围要是在我们最先选定的那个数之后的。而计算则同样是先选一个数,然后再剩下的数中计算。 2Sum 在分析多数和之前,请先看Two Sum的详解 3Sum 请参阅:https://yanjia.me/zh/2019/01/... 双指针法 复杂度 时间 O(N^2) 空间 O(1) 思路 3Sum其实可以转化成一个2Sum的题,...

    trigkit4 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<