Solution of Sum With Multiplicity

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

As the answer can be very large, return it modulo 10^9 + 7.

Example 1:

Input: A = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20

==Explanation: ==
Enumerating by the values (A[i], A[j], A[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: A = [1,1,2,2,2,2], target = 5
Output: 12

==Explanation: ==
A[i] = 1, A[j] = A[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.

Note:

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

Ideas of solving problems

The brute force method is divided into three cases, two Numbers are the same, three Numbers are the same and three Numbers are not the same, and then narrow the loop upper and lower bounds. If you have the same number, the maximum you can do is not greater than target over 2. If all three Numbers are different, the smallest number is not greater than target over 3 and the second number is not greater than target over 2.
Since it’s not divisible, everything is given a plus 1 in case there’s a number that doesn’t loop. The time complexity is O(n^3), and the space complexity is O(1). The memory consumption is 3.2Mb.

Code

func threeSumMulti(A []int, target int) int {
   sts:=make([]int,101) 
   for i:=0;i<len(A);i++{
       sts[A[i]]++
   }
   count:=0
   if target%3==0&&sts[target/3]>=3{
       fmt.Println(sts[target/3],sts[target/3]*(sts[target/3]-1)*(sts[target/3]-2)/6)
       count+=sts[target/3]*(sts[target/3]-1)*(sts[target/3]-2)/6
   }
   for i:=0;i<len(sts)&&i<target/2+1;i++{
       if(target-2*i<=100&&target-2*i>=0&&sts[i]>=2&&sts[target-2*i]!=0&&(target-2*i)!=i){
           count+=sts[i]*(sts[i]-1)*sts[target-2*i]/2
       }
   }
   for i:=0;i<len(sts)-2&&i<target/3+1;i++{
       for j:=i+1;j<len(sts)-1&&i<target/2+1;j++{
           for m:=j+1;m<len(sts)&&m<target;m++{
               if(i+j+m==target){
                   count+=sts[i]*sts[j]*sts[m]
               }
           }
       }
   }
   return count%1000000007
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-with-multiplicity/solution/bao-li-po-jie-by-jiangyy-4/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值