923. 3Sum With Multiplicity

Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.

As the answer can be very large, return it modulo 109 + 7.

Example 1:

Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
Explanation: 
Enumerating by the values (arr[i], arr[j], arr[k]):
(1, 2, 5) occurs 8 times;
(1, 3, 4) occurs 8 times;
(2, 2, 4) occurs 2 times;
(2, 3, 3) occurs 2 times.

Example 2:

Input: arr = [1,1,2,2,2,2], target = 5
Output: 12
Explanation: 
arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:
We choose one 1 from [1,1] in 2 ways,
and two 2s from [2,2,2,2] in 6 ways.

Example 3:

Input: arr = [2,1,3], target = 6
Output: 1
Explanation: (1, 2, 3) occured one time in the array so we return 1.

Constraints:

  • 3 <= arr.length <= 3000
  • 0 <= arr[i] <= 100
  • 0 <= target <= 300

题目:给定一个数组,找处其中三元组的个数,使三元组加和为target,允许有重复。

思路:与1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers类似,只是1577是找两个元素,这里找三个元素;1577是相乘,这里是相加。用map来存储元素个数,然后双指针找就可以了。因为题目说arr[i] <= 100,因此用vector来代替map,开销小一些。主要注意数据溢出情况。

代码:

class Solution {
public:
    int threeSumMulti(vector<int>& arr, int target) {
        vector<long> record(101, 0);
        for(auto n : arr){
            record[n]++;
        }
        long res = 0, mod = 1000000007;
        for(int i = 0; i <= target/3; i++){
            if(record[i] == 0) continue;
            int j = record[i]==1?i+1:i, k = 100;
            while(j <= k){
                while(j <= k && record[j] == 0) j++;
                while(j <= k && record[k] == 0) k--;
                if(j > k || (j==k && record[j]==1)) break;
                int sum = i + j + k;
                if(sum > target) k--;
                else if(sum < target) j++;
                else {
                    long temp = 0;
                    if(i==j && j==k && record[i] >= 3) 
                        temp = (record[i]*(record[i]-1)*(record[i]-2) / 6) % mod;
                    else if(i == j && j != k && record[i] >= 2 ) 
                        temp = (record[k] * record[i] *(record[i]-1) / 2) % mod;
                    else if(i != j && j == k && record[j] >= 2)
                        temp = (record[i] * (record[j] * (record[j]-1)) / 2) % mod;
                    else if(i != j && j != k)
                        temp = (record[i] * record[j] * record[k]) % mod;
                    res = (res + temp) % mod;
                    j++;
                    k--;
                }
            }
        }
        return (int)res;
    }
};

time:O(N), spaceO(1)。因为record是定长的,时间复杂度主要在生成record的时候。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值