做这道题前需要先做:LeetCode 15. 3Sum–Java,Python解法
题目地址:3Sum With Multiplicity - LeetCode
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
python解法:
class Solution:
def threeSumMulti(self,A = [1,1,2,2,3,3,4,4,5,5], target = 8) -> int:
A.sort()
numCount={}
res=0
numSet=[]
for i in A:
if i not in numCount:
numCount[i]=1
numSet.append(i)
else:
numCount[i]+=1
if numCount[i]<=3:
numSet.append(i)
length=len(numSet)
for i in range(0,length-2):
if numSet[i]>target:
break
if i>0 and numSet[i]==numSet[i-1]:
continue
l, r = i+1, length-1
while l<r:
total=numSet[i]+numSet[l]+numSet[r]
if total<target:
l+=1
elif total>target:
r-=1
else:
a=numCount[numSet[i]]
numCount[numSet[i]]-=1
b=numCount[numSet[l]]
numCount[numSet[l]]-=1
c=numCount[numSet[r]]
numCount[numSet[r]]-=1
if numSet[i]==numSet[l]==numSet[r]:
res+=a*b*c//6
elif numSet[i]==numSet[l] or numSet[l]==numSet[r]:
res+=a*b*c//2
else:
res+=a*b*c
numCount[numSet[r]]+=1
numCount[numSet[l]]+=1
numCount[numSet[i]]+=1
while l<r and numSet[l]==numSet[l+1]:
l+=1
while l<r and numSet[r]==numSet[r-1]:
r-=1
l+=1
r-=1
return res%(10**9+7)
优化后的Python代码:
class Solution(object):
def threeSumMulti(self, A, target):
MOD = 10**9 + 7
count = collections.Counter(A)
keys = sorted(count)
ans = 0
# Now, let's do a 3sum on "keys", for i <= j <= k.
# We will use count to add the correct contribution to ans.
for i, x in enumerate(keys):
T = target - x
j, k = i, len(keys) - 1
while j <= k:
y, z = keys[j], keys[k]
if y + z < T:
j += 1
elif y + z > T:
k -= 1
else: # x+y+z == T, now calculate the size of the contribution
if i < j < k:
ans += count[x] * count[y] * count[z]
elif i == j < k:
ans += count[x] * (count[x] - 1) / 2 * count[z]
elif i < j == k:
ans += count[x] * count[y] * (count[y] - 1) / 2
else: # i == j == k
ans += count[x] * (count[x] - 1) * (count[x] - 2) / 6
j += 1
k -= 1
return int(ans % MOD)
java代码如下: