四数之和

 

 https://leetcode.cn/problems/4sum-ii/solution/si-shu-xiang-jia-ii-by-leetcode-solution/

 

 

 

时间复杂度和空间复杂度都是O(n2)

func fourSumCount(a, b, c, d []int) (ans int) {
    mp:=make(map[int]int,0)
    for i:=0;i<len(a);i++{
        for j:=0;j<len(b);j++{
            mp[a[i]+b[j]]++ 
        }
    }
   
    for i:=0;i<len(c);i++{
        for j:=0;j<len(d);j++{
            ans=ans+mp[-1*(c[i]+d[j])] //相反数出现的次数,组合起来就是最终结果
        }
    }
    return ans
}

 

 

 
posted @ 2022-07-06 17:48  知道了呀~  阅读(61)  评论(0编辑  收藏  举报