0数学/数组简单 LeetCode1995. 统计特殊四元组

1995. 统计特殊四元组

描述

给你一个 下标从 0 开始 的整数数组 nums ,返回满足下述条件的 不同 四元组 (a, b, c, d) 的 数目 :
nums[a] + nums[b] + nums[c] == nums[d] ,且
a < b < c < d

分析

题目是两数之和的变种题目。
转换成两半,一半是D-C,一半是A+B,分别遍历这两半如果相等,则说明满足满足条件。
D-C用map集合存储,健是D-C,值是D-C的个数。
遍历B,在确定B的情况下,与B+1相比,此时C的取值范围多了B+1这种情况,遍历D,计算D-C,添加到map集合中。

class Solution {
    public int countQuadruplets(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        int n = nums.length;
        int ans = 0;
        for(int i = n - 3; i >= 1; i--){
            for(int j = i + 2; j < n; j++){
                int tmp = (nums[j] - nums[i+1]);
                map.put(tmp, map.getOrDefault(tmp,0) + 1);
            }
            for(int k = 0; k < i; k++){
                int temp = nums[i] + nums[k];
                ans += map.getOrDefault(temp,0);
            }
        }
        return ans;
    }
}

你可能感兴趣的:(leetcode,算法,数据结构)