给你一个下标从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
Python解答:
class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
lens = len(nums)
total = 0
for i in range(lens-3):
for j in range(i+1, lens-2):
for k in range(j+1, lens-1):
for d in range(k+1, lens):
if nums[i]+nums[j]+nums[k] == nums[d]:
total += 1
return total
Java解答:
class Solution {
public int countQuadruplets(int[] nums) {
int total = 0;
for(int i = 0; i < nums.length-3; i++)
{
for(int j = i+1; j < nums.length-2; j++)
{
for(int k = j+1; k < nums.length-1; k++)
{
for(int d = k+1; d < nums.length; d++)
{
if(nums[i] + nums[j] + nums[k] == nums[d])
total += 1;
}
}
}
}
return total;
}
}
留言