3Sum With Multiplicity
Medium
Given an integer arrayA, and an integertarget, return the number of tuples i, j, k such thati < j < kand 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 <= 30000 <= A[i] <= 1000 <= target <= 300
Solution
Approach 1: Three Pointer
NSum问题很自然地想到用 N(Two) Pointers
Sort the array.
For each
i, setT = target - A[i], the remaining target.We can try using a two-pointer technique to find
A[j] + A[k] == T.
Whenever A[j] + A[k] == T, we should count the multiplicity of A[j] and A[k].
因为有重复元素,我们需要特别小心。在A[j] + A[k] == T时,我们要分两种情况计算multiplicity:
A[j] == A[k],这个是说明A[j],A[k]本身都在同一个重复元素序列中,并且一个是头一个是尾,这样根据组合数的计算C(n, 2),即n个元素取2个,有n (n - 1) / 2种,因此结果count += (j - k + 1) * (j - k) / 2;A[j] != A[k],这个时候A[j],A[k]不在同一个重复元素序列中,但是本身可能会有重复,因此另设计数变量left,right,分别记录A[j],A[k]有多少次重复,最后计算两者相乘即可,即count += left * right;
LeetCode Solution
My Version (63 ms, 53.40%)
Time Complexity: O(N^2), where N is the length of A.
Space Complexity: O(1).
Approach 2: Adapt from Three Sum
HashMap - Store number of occurrence (17ms, 73.79%)
Approach 3: Think outside of the box - build a map for counting different sums of two numbers
外层循环i,内层循环j,内层循环不断更新A[i] + A[j] two sum对应的计数,外层i在下一个循环时,则相当于第三个index k,若找到target - A[i]就更新结果。
Time - O(N^2), Space - O (N^2)(590 ms, faster than 9.71%)
Reference
https://leetcode.com/problems/3sum-with-multiplicity/solution/
Last updated
Was this helpful?