原题链接在这里:
题目:
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 = 8Output: 20Explanation: 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 = 5Output: 12Explanation: 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
题解:
Perform and find the target.
Here there are 2 cases:
1. A[l] != A[r], count the frequency of A[l] and A[r], possible number of tuples is leftCount*rightCount.
e.g. 2333, A[l] = 2, A[r] = 3, leftCount = 1, rightCount = 3, number of types is 1*3 = 3.
2. A[l] == A[r], number of tupes is count*(count-1)/2.
e.g. 222, A[l] = 2, A[r] = 2, number of tupes 3*2/2 = 3. There are 3 ways to pick 2 elements from it.
Time Compelxity: O(n^2). n = A.length.
Space: O(1).
AC Java:
1 class Solution { 2 public int threeSumMulti(int[] A, int target) { 3 if(A == null || A.length == 0){ 4 return 0; 5 } 6 7 int res = 0; 8 int M = 1000000000+7; 9 Arrays.sort(A);10 for(int i = 0; itarget){18 r--;19 }else if(A[l] != A[r]){20 int leftCount = 1;21 int rightCount = 1;22 while(l+1