4Sum II

原题: https://leetcode.com/problems/4sum-ii/description/

题意: 给定4个整数列表A, B, C, D,计算有多少个元组 (i, j, k, l) 满足 A[i] + B[j] + C[k] + D[l] = 0。

约定: (1)A, B, C, D相等都是N, 0 ≤ N ≤ 500 (2)所有整数在范围 [-2^28 , 2^28 - 1] 之内,并且结果确保至多为 2^31 - 1

例子: 

输入:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

输出:2

说明:
这两个元组是:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

标签: 4sum、元组、ii、至多、之内、面试
猜你感兴趣的圈子:
LeetCode交流圈
  • 星空
    2017-08-18 18:06:59 1楼#1层
    class Solution(object):
        def fourSumCount(self, A, B, C, D):
            """
            :type A: List[int]
            :type B: List[int]
            :type C: List[int]
            :type D: List[int]
            :rtype: int
            """
            ans = 0
            cnt = collections.defaultdict(int)
            for a in A:
                for b in B:
                    cnt[a + b] += 1
            for c in C:
                for d in D:
                    ans += cnt[-(c + d)]
            return ans
  • 星空
    2017-08-18 18:07:42 2楼#1层
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        Map<Integer, Integer> map = new HashMap<>();
        
        for(int i=0; i<C.length; i++) {
            for(int j=0; j<D.length; j++) {
                int sum = C[i] + D[j];
                map.put(sum, map.getOrDefault(sum, 0) + 1);
            }
        }
        
        int res=0;
        for(int i=0; i<A.length; i++) {
            for(int j=0; j<B.length; j++) {
                res += map.getOrDefault(-1 * (A[i]+B[j]), 0);
            }
        }
        
        return res;
    }
  • 星空
    2017-08-18 18:08:35 3楼#1层
    class Solution(object):
       def fourSumCount(self, A, B, C, D):
        AB = collections.Counter(a+b for a in A for b in B)
        return sum(AB[-c-d] for c in C for d in D)
  • 回复
隐藏