leetcode:ハッシュテーブル454 4Sum II

タイトル

何組の整数値、計算の4つのリストA、B、C、D、所与の  (i, j, k, l) ように存在する  A[i] + B[j] + C[k] + D[l] ゼロです。

1結果が最も231であることが保証される - ビット容易問題を作るために、すべてのA、B、C、Dは、0≤N≤500のすべての整数は-228〜228の範囲内にあるNの同じ長さを有します - 1。

例:

入力: 
A = [1、2] 
B = [-2、-1] 
C = [-1、2] 
D = [0,2] 出力: 
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



思考

暴力:別々に各アレイを介して

答え

class Solution:
    def fourSumCount(self, A, B,C,D) -> int:
        def twoSumCount(target):
            count = 0
            h = 0
            k = len(D) - 1
            while h<len(C) and k>=0:
                sumNum = C[h] + D[k]
                if sumNum<target:
                    h += 1
                    while h<len(C) and C[h] == C[h-1]:
                        h += 1
                elif sumNum>target:
                    k -= 1
                    while k>=0 and D[k] == D[k+1]:
                        k-=1
                else:
                    c1 = 1
                    h += 1
                    while h<len(C) and C[h] == C[h-1]:
                        h += 1
                        c1 += 1
                    c2 = 1
                    k -= 1
                    while k>=0 and D[k] == D[k+1]:
                        k-=1
                        c2 += 1
                    count += c1*c2
            return count
        
        n = len(A)
        A,B,C,D = sorted(A),sorted(B),sorted(C),sorted(D)
        count = 0
        target = 0
        i = 0
        while i < n:
            count2 = 0
            j = 0
            while j < n:
                count_temp = twoSumCount(target-A[i]-B[j]) 
                j += 1
                c2 = 1
                if count_temp >0:
                    while j<n and B[j]==B[j-1]:
                        j += 1
                        c2 += 1
                    count2 += count_temp*c2
            i += 1
            c1 = 1
            if count2:
                while i<n and A[i]==A[i-1]:
                    i += 1
                    c1 += 1
                count += count2*c1
            
                    
        return count

 

今回出て、これは時間のハッシュテーブルを削減するために使用することができます。4Sum唯一の問題は、アレイとは異なる、アレイは4です。だから、基本的に2つの数字がプラス、それは同じとなっています。私はいつものテーブルがあり、数えるし始め、再びカウントされません。そして、うまく拾います。

class Solution:
    def fourSumCount(self, A, B,C,D) -> int:
        AB = collections.defaultdict(lambda:0)
        for a in A:
            for b in B:
                AB[a+b] += 1
        count = 0
        keys = AB.keys()
        for c in C:
            for d in D:
                if -c-d in keys:
                    count += AB[-c-d]
            
        return count

 

发布了45 篇原创文章 · 获赞 1 · 访问量 3371

おすすめ

転載: blog.csdn.net/qq_22498427/article/details/104504813