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

Code

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

        Arrays.sort(nums);

        int max = nums[len - 1];
        if (4 * nums[0] > target || 4 * max < target)
            return res;

        int i, z;
        for (i = 0; i < len; i++) {
            z = nums[i];
            if (i > 0 && z == nums[i - 1])// avoid duplicate
                continue;
            if (z + 3 * max < target) // z is too small
                continue;
            if (4 * z > target) // z is too large
                break;
            if (4 * z == target) { // z is the boundary
                if (i + 3 < len && nums[i + 3] == z)
                    res.add(Arrays.asList(z, z, z, z));
                break;
            }

            threeSumForFourSum(nums, target - z, i + 1, len - 1, res, z);
        }

        return res;
    }

    /*
     * Find all possible distinguished three numbers adding up to the target
     * in sorted array nums[] between indices low and high. If there are,
     * add all of them into the ArrayList fourSumList, using
     * fourSumList.add(Arrays.asList(z1, the three numbers))
     */
    public void threeSumForFourSum(int[] nums, int target, int low, int high, ArrayList<List<Integer>> fourSumList,
            int z1) {
        if (low + 1 >= high)
            return;

        int max = nums[high];
        if (3 * nums[low] > target || 3 * max < target)
            return;

        int i, z;
        for (i = low; i < high - 1; i++) {
            z = nums[i];
            if (i > low && z == nums[i - 1]) // avoid duplicate
                continue;
            if (z + 2 * max < target) // z is too small
                continue;

            if (3 * z > target) // z is too large
                break;

            if (3 * z == target) { // z is the boundary
                if (i + 1 < high && nums[i + 2] == z)
                    fourSumList.add(Arrays.asList(z1, z, z, z));
                break;
            }

            twoSumForFourSum(nums, target - z, i + 1, high, fourSumList, z1, z);
        }

    }

    /*
     * Find all possible distinguished two numbers adding up to the target
     * in sorted array nums[] between indices low and high. If there are,
     * add all of them into the ArrayList fourSumList, using
     * fourSumList.add(Arrays.asList(z1, z2, the two numbers))
     */
    public void twoSumForFourSum(int[] nums, int target, int low, int high, ArrayList<List<Integer>> fourSumList,
            int z1, int z2) {

        if (low >= high)
            return;

        if (2 * nums[low] > target || 2 * nums[high] < target)
            return;

        int i = low, j = high, sum, x;
        while (i < j) {
            sum = nums[i] + nums[j];
            if (sum == target) {
                fourSumList.add(Arrays.asList(z1, z2, nums[i], nums[j]));

                x = nums[i];
                while (++i < j && x == nums[i]) // avoid duplicate
                    ;
                x = nums[j];
                while (i < --j && x == nums[j]) // avoid duplicate
                    ;
            }
            if (sum < target)
                i++;
            if (sum > target)
                j--;
        }
        return;
    }

MyCode

class Solution {
    public List<List<Integer>> fourSum(int[] num, int target) {
        Arrays.sort( num );
        List<List<Integer>> rt = new LinkedList<>();
        int sum = 0;

        for ( int i = 0 ;i< num.length -3;i++){
            if( i == 0 || (i> 0 && num[i] != num[i-1]) )
            for( int j = i + 1;j< num.length - 2 ; j++){
                if( j == 1 || j==i+1 && num[j]== num[i]||(j>1 &&num[j]!=num[j-1])){
                    sum = target - num[i] - num[j];
                    int lo = j + 1;
                    int hi = num.length-1;
                    while( lo < hi ){
                        if( num[lo] + num[hi] == sum ){
                            rt.add(( Arrays.asList(num[i],num[j],num[lo],num[hi])));
                            while( lo < hi && num[hi]==num[hi-1]) hi--;
                            while( lo < hi && num[lo]==num[lo+1]) lo++;
                            lo++;hi--;
                        }else if( num[lo] + num[hi] < sum)
                            lo++;
                        else hi--;
                    }
                }
            }
        }
        return rt;
    }
}

问题

完全是仿照3sum的思路写的,但是思路更加复杂,最后的逻辑可以说是凑出来的,并不能完全理通顺(Mycode)

<think> 在用户的问题中,用户提到“我想了解Sum的运用”,并询问“Sum的运用方法”。结合用户提供的引用内容,我需要从多个角度解释Sum函数的应用,包括Excel、编程语言(如C++、Python)和SQL中的用法。 首先,引用[1]展示了在Excel中Sum与CountIf的组合使用,用于统计满足特定条件的数值。例如,计算大于等于5万但小于8万的数值个数,可以通过先计算大于等于5万的个数,再减去大于8万的个数来实现。 引用[2]和[4]分别涉及MATLAB和NumPy中Sum函数的数组运算,特别是多维数组的求和,以及axis参数的使用。 引用[3]则介绍了C++中的partial_sum算法,用于计算部分和。 引用[5]展示了SQL中Count和Sum的运用,用于统计数据库中的数据。 因此,我将从以下几个方面组织回答: 1. Excel中Sum函数的运用(包括组合使用) 2. 编程语言中Sum的运用(包括C++、Python等) 3. SQL中Sum函数的运用 4. 多维数组求和(如NumPy)中axis参数的理解 同时,根据系统级指令,我需要使用正确的Latex格式,并且生成相关问题。 注意:由于用户是中文提问,全部使用中文回答。 下面开始组织答案: </think> ### Sum函数的运用方法 Sum函数是数据分析和编程中常用的聚合工具,用于计算数值的总和。根据引用内容,其核心用法可分为以下场景: #### 1. **Excel中的Sum函数** - **基础求和**:`=SUM(范围)` 计算指定单元格的和,如 `=SUM(A1:A5)`。 - **结合条件函数**(引用[1]): - **与CountIf组合**:统计满足多条件的数量。 ```excel =SUM(COUNTIF(范围, {条件1, 条件2})) // 统计同时满足多个条件的数量 ``` - **与If组合**:例如统计5万到8万之间的数值数量: ```excel =SUM(COUNTIF(范围, ">=50000") - COUNTIF(范围, ">80000")) // 结果为满足区间条件的数量 ``` 原理:先计算≥5万的个数,再减去>8万的个数,得到区间值(如结果为3)[^1]。 #### 2. **编程中的Sum函数** - **C++部分和计算**(引用[3]): `partial_sum()` 生成序列的部分和(累加和): ```cpp #include <numeric> vector<int> arr = {1, 2, 3, 4}; vector<int> result(4); partial_sum(arr.begin(), arr.end(), result.begin()); // 输出:{1, 3, 6, 10} ``` - **Python/NumPy多维数组求和**(引用[4]): 通过 `axis` 参数控制求和维度: ```python import numpy as np arr = np.array([[[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]]]) np.sum(arr, axis=0) # 沿第一个维度求和 → [[8,10,12], [14,16,18]] np.sum(arr, axis=1) # 沿第二个维度求和 → [[5,7,9], [17,19,21]] ``` 规则:`axis=k` 表示压缩第k个维度,对剩余维度求和[^4]。 - **MATLAB数组求和**(引用[2]): ```matlab a = [1,2,3; 4,5,6]; sum(a) % 按列求和 → [5,7,9] sum(a, 2) % 按行求和 → [6; 15] sum(a(:)) % 全矩阵求和 → 21 ``` #### 3. **SQL中的Sum函数**(引用[5]) 用于统计字段总和,常结合 `GROUP BY`: ```sql -- 计算每个学生(sno)的总分 SELECT sno, SUM(score) AS total_score FROM scores GROUP BY sno; ``` 输出示例: | sno | total_score | |------|-------------| | s001 | 220.8 | | s002 | 153.8 | #### 4. **关键技巧** - **多维求和**:明确 `axis` 维度方向(如NumPy中 `axis=0` 为沿行方向求和)[^4]。 - **条件统计**:通过组合函数(如Excel中 `COUNTIF` 嵌套 `SUM`)实现区间统计[^1]。 - **部分和应用**:在序列处理中生成累加结果(如C++ `partial_sum`)[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值