923. 3Sum With Multiplicity

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/83045443

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:

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

思路:ijk顺序什么的,其实无所谓

因为就3个数,考虑以下3种情况:

1. 3个数都不同(注意除以6出掉重复)

2. 2个数相同

3. 3个数都相同

class Solution(object):
    def threeSumMulti(self, A, target):
        """
        :type A: List[int]
        :type target: int
        :rtype: int
        """
        mod=10**9+7
        res=0
        a=A
        d={}
        for i in a: d[i]=d.get(i,0)+1
        
        for i in d:
            for j in d:
                if i==j or target-i-j==i or target-i-j==j or target-i-j not in d: continue
                res+=d[i]*d[j]*d[target-i-j]
        res//=6
#        print(res)
        for i in d:
            if d[i]<2 or target-i-i==i or target-i-i not in d: continue
            res+=(d[i]*(d[i]-1)//2)*d[target-i-i]
#        print(res)
        for i in d:
            if d[i]<3 or target!=i*3: continue
            res+=d[i]*(d[i]-1)*(d[i]-2)//6
        
        
        return res%mod
    
s=Solution()
print(s.threeSumMulti(A = [1,1,2,2,3,3,4,4,5,5], target = 8))
print(s.threeSumMulti(A = [1,1,2,2,2,2], target = 5))
print(s.threeSumMulti(A = [16,51,36,29,84,80,46,97,84,16], target = 171))

猜你喜欢

转载自blog.csdn.net/zjucor/article/details/83045443
今日推荐