LeetCode 2964. 可被整除的三元组数量

2964. 可被整除的三元组数量

给定一个 下标从 0 开始 的整数数组 nums 和一个整数 d,请返回满足 i < j < k 且 (nums[i] + nums[j] + nums[k]) % d == 0 的三元组 (i, j, k) 的数量。

示例 1:

输入:nums = [3,3,4,7,8], d = 5
输出:3
解释:可以被5整除的三元组有:(0, 1, 2),(0, 2, 4),(1, 2, 4)。其他没有其他能被5整除的三元组。因此,答案是3。

示例 2:

输入:nums = [3,3,3,3], d = 3
输出:4
解释:这里选择的任何三元组的和都是9,可以被3整除。因此,答案是所有三元组的总数,即4。

示例 3:

输入:nums = [3,3,3,3], d = 6
输出:0
解释:这里选择的任何三元组的和都是9,不能被6整除。因此,答案是0。

提示:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 10^9
  • 1 <= d <= 10^9

提示 1

Fix index L to be the leftmost element of a triplet.


提示 2

Starting from L, go forward and add the remainder of each element to a map.


提示 3

Now when you are at index R, consider nums[L] + nums[R] and calculate what the remainder of the third element should be.


提示 4

Then use the map to find the number of valid third elements between L and R.

解法:枚举k

我们将 (nums[i] + nums[j]) % d 的值存放在数组map中,遍历 k, 找到 map 中 (d - nums[k] % d) % d 的值的数量,并累加到答案ans上,这样满足 (nums[i] + nums[j] + nums[k]) % d == 0。

类似题型:

LeetCode 1. 两数之和-CSDN博客

LeetCode 1814. 统计一个数组中好对子的数目-CSDN博客

LeetCode 2874. 有序三元组中的最大值 II-CSDN博客

LeetCode 2971. 找到最大周长的多边形-CSDN博客

LeetCode 2748. 美丽下标对的数目-CSDN博客

LeetCode 18. 四数之和-CSDN博客

LeetCode 15. 三数之和-CSDN博客

Java版:

class Solution {
    public int divisibleTripletCount(int[] nums, int d) {
        int n = nums.length;
        if (n < 3) {
            return 0;
        }
        // 0 <= i < j < k <= n - 1
        int[] map = new int[d];
        map[(nums[0] + nums[1]) % d] = 1;
        int ans = 0;
        for (int k = 2; k <= n - 1; k++) {
            nums[k] %= d;
            int x = (d - nums[k]) % d;
            ans += map[x];

            for (int l = k - 1; l >= 0; l--) {
                map[(nums[l] + nums[k]) % d]++;
            }
        }
        
        return ans;
    }
}

Python3版:

class Solution:
    def divisibleTripletCount(self, nums: List[int], d: int) -> int:
        n = len(nums)
        if n < 3:
            return 0
        ans = 0
        map_ = [0] * d
        map_[ (nums[0] + nums[1]) % d ] = 1
        for k in range(2, n):
            nums[k] %= d
            x = (d - nums[k]) % d
            ans += map_[x]

            for l in range(k - 1, -1, -1):
                x = (nums[l] + nums[k]) % d
                map_[x] += 1
        return ans 

复杂度分析

  • 时间复杂度:O(n),其中 n 为数组 nums 的大小。我们只需要遍历一遍数组即可。
  • 空间复杂度:O(d)。我们需要长度为 d 的数组来存放变量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值