Formatted question description: https://leetcode.ca/all/923.html

# 923. 3Sum With Multiplicity (Medium)

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

Companies:
Quora

Related Topics:
Two Pointers

## Solution 1.




Java

class Solution {
public int threeSumMulti(int[] A, int target) {
final int MODULO = 1000000007;
long count = 0;
Arrays.sort(A);
int length = A.length;
int leftStart = 0, leftEnd = length - 3;
for (int left = leftStart; left <= leftEnd; left++) {
if (A[left] > target)
break;
int remainTarget = target - A[left];
int mid = left + 1, right = length - 1;
while (mid < right) {
int sum = A[mid] + A[right];
if (sum == remainTarget) {
if (A[mid] != A[right]) {
int midCount = 1, rightCount = 1;
while (mid + 1 < right && A[mid] == A[mid + 1]) {
mid++;
midCount++;
}
while (right - 1 > mid && A[right] == A[right - 1]) {
right--;
rightCount++;
}
count += midCount * rightCount;
count %= MODULO;
mid++;
right--;
} else {
int curCount = right - mid + 1;
count += curCount * (curCount - 1) / 2;
count %= MODULO;
break;
}
} else if (sum < remainTarget)
mid++;
else
right--;
}
}
return (int) count;
}
}