当前位置:网站首页>November 15, 2021: add four numbers II. Here are four integer arrays nums1, num

November 15, 2021: add four numbers II. Here are four integer arrays nums1, num

2022-06-24 01:43:00 Fuda scaffold constructor's daily question

2021-11-15: Add four numbers II. Here are four integer arrays nums1、nums2、nums3 and nums4 , The length of the array is n , Please calculate how many tuples there are (i, j, k, l) To meet the :0 <= i, j, k, l < n;nums1i + nums2j + nums3k + nums4l == 0. Power button 454.

answer 2021-11-15:

nums1+nums2 save map. Then seek nums3 +nums4 , stay map Find the opposite number in , Just add it to the results .

Time complexity :O(N**2).

Extra space complexity :O(N**2).

The code to use golang To write . The code is as follows :

package main

import "fmt"

func main() {
    nums1 := []int{1, 2}
    nums2 := []int{-2, -1}
    nums3 := []int{-1, 2}
    nums4 := []int{0, 2}
    ret := fourSumCount(nums1, nums2, nums3, nums4)
    fmt.Println(ret)

}

func fourSumCount(A, B, C, D []int) int {
    map0 := make(map[int]int)
    sum := 0
    for i := 0; i < len(A); i++ {
        for j := 0; j < len(B); j++ {
            sum = A[i] + B[j]
            map0[sum]++

        }
    }
    ans := 0
    for i := 0; i < len(C); i++ {
        for j := 0; j < len(D); j++ {
            sum = C[i] + D[j]
            if _, ok := map0[-sum]; ok {
                ans += map0[-sum]
            }
        }
    }
    return ans
}

The results are as follows :

picture

Zuo Shen java Code

原网站

版权声明
本文为[Fuda scaffold constructor's daily question]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/11/20211116100159649B.html