LeetCode周賽#106 Q3 3Sum With Multiplicity (計數排序)
阿新 • • 發佈:2018-11-10
題目來源:https://leetcode.com/contest/weekly-contest-106/problems/3sum-with-multiplicity/
問題描述
923. 3Sum 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
------------------------------------------------------------
題意
給定一組數,求其中三個數a1+a2+a3=target的可能的組合方式,要求三個數的數值可以相同,但必須是升序
------------------------------------------------------------
思路
注意到陣列中的數的取值範圍(0~100)遠小於陣列長度(0~3000),故首先用計數排序把原數列轉化為0~100中各個數出現的個數。然後分“a1<a2<a3”“a1<a2=a3”“a1=a2<a3”“a1=a2=a3”討論。
注意儘管1e9+7在int範圍內,但結果一次增加的數值有可能超過int,所以結果和計數排序的陣列都要用long long.
------------------------------------------------------------
程式碼
class Solution {
public:
const int MOD = (int)(1e9 + 7);
long long n;
long long a[105];
int threeSumMulti(vector<int>& A, int target) {
n = 0;
int i, j, k, len = A.size();
for (i=0; i<len; i++)
{
a[A[i]]++;
}
for (i = 0; i < 105; i++)
{
for (j = i+1; j < 105; j++)
{
for (k = j+1; k < 105; k++)
{
if (a[i] > 0 && a[j] > 0 && a[k] > 0 && i+j+k == target)
{
n += a[i]*a[j]*a[k];
n %= MOD;
}
}
}
}
for (i=0; i<105; i++)
{
for (j=i+1; j<105; j++)
{
if (a[j]>=2 && a[i]>0 && i+2*j==target)
{
n += a[i]*a[j]*(a[j]-1)/2;
n %= MOD;
}
}
}
for (i=0; i<105; i++)
{
for (j=i+1; j<105; j++)
{
if (a[j]>0 && a[i]>=2 && 2*i+j==target)
{
n += a[j]*a[i]*(a[i]-1)/2;
n %= MOD;
}
}
}
for (i=0; i<105; i++)
{
if (a[i] >=3 && 3*i == target)
{
n += a[i]*(a[i]-1)*(a[i]-2)/6;
n %= MOD;
}
}
return n;
}
};