题目描述
给你一个 下标从 0 开始 的整数数组 nums ,返回满足下述条件的 不同 四元组 (a, b, c, d) 的 数目 :
nums[a] + nums[b] + nums[c] == nums[d] ,且a < b < c < d
示例 1:
输入:nums = [1,2,3,6]
输出:1
解释:满足要求的唯一一个四元组是 (0, 1, 2, 3) 因为 1 + 2 + 3 == 6 。
示例 2:
输入:nums = [3,3,6,4,5]
输出:0
解释:[3,3,6,4,5] 中不存在满足要求的四元组。
示例 3:
输入:nums = [1,1,1,3,5]
输出:4
解释:满足要求的 4 个四元组如下:
- (0, 1, 2, 3): 1 + 1 + 1 == 3
- (0, 1, 3, 4): 1 + 1 + 3 == 5
- (0, 2, 3, 4): 1 + 1 + 3 == 5
- (1, 2, 3, 4): 1 + 1 + 3 == 5
提示:
4 <= nums.length <= 50
1 <= nums[i] <= 100
思路:
可以暴力,因为length<=50。
或者用哈希表,方法如下:
class Solution {
public int countQuadruplets(int[] nums) {
int n = nums.length;
int anw = 0;
//哈希表存d和d对应的数量
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//对c逆序
for(int c = nums.length - 2; c >= 2; c--){
//把d put到map中
map.put(nums[c + 1], map.getOrDefault(nums[c + 1], 0) + 1);
for(int a = 0; a < c - 1; a++)
for(int b = a + 1; b < c; b++){
//如果 a+b+c 能在哈希表中找到值,找到的值表示d对应的数量。
anw = anw + map.getOrDefault((nums[c] + nums[b] + nums[a]),0);
}
}
return anw;
}
}