Skip to content

Latest commit

 

History

History
63 lines (47 loc) · 1.61 KB

923. 3Sum With Multiplicity.md

File metadata and controls

63 lines (47 loc) · 1.61 KB

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.

注意:一定要看清问题,i<j<k 并且要求余数。

import itertools
class Solution(object):
    def threeSumMulti(self, A, target):
        c = collections.Counter(A)
        print(c)
        res = 0
        for i, j in itertools.combinations_with_replacement(c, 2):
            print(i,j)
            k = target - i - j 
            if i == j == k: res += c[i] * (c[i] - 1) * (c[i] - 2) / 6
            elif i == j != k: res += c[i] * (c[i] - 1) / 2 * c[k]
            elif k > i and k > j: res += c[i] * c[j] * c[k]
        return int(res % (10**9 + 7))

考虑一下collections模块,主要针对字典等数据结构

算法思路:

  1. 先将list里面的元素改为字典的结构;

  2. itertools.combinations_with_replacement(c, 2):在字典里面取两个值,组成对

  3. 注意题目的条件是i<j<k,所以每个元素只能用一次:

    i=j=k

    i=j!=k

    i!=j<k

    没有小于的部分,否则重复。要好好思考!!!