Leetcode 454. 4Sum II

给定四个整数列表 A、B、C 和 D,计算有多少四元组 (i, j, k, l) 使得 A[i] + B[j] + C[k] + D[l] = 0。所有列表具有相同的长度 N,且 0 ≤ N ≤ 500,数值范围在 -2^31 到 2^31 - 1 之间,结果不超过 2^31 - 1。该问题的关键在于利用两个两两元素之和的列表来提高时间效率,通过构建一个计数器,将查找时间降低到常数级别,实现 O(N^2) 的时间复杂度解决方案。" 105326434,5673235,STM32驱动DTH11温湿度模块实战,"['stm32开发', '嵌入式硬件', '传感器驱动', '微控制器应用', '单总线通信']

问题

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example:

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

Output:
2

Explanation:
The two tuples are:
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最大的不同是:4Sum需要在一个列表中找四个不同的元素,而本题需要在每个列表中各找一个元素。相当于4Sum有四个列表,但列表不是相互独立的;本题有四个列表,列表是相互独立的。这就造成了本题的时间复杂度比4Sum要低。

构造A, B两两元素之和的列表combine1, C,D两两元素之和的列表combine2,则问题变成了从combine1找一个值value1,从combine2找一个值value2,使得value1 + value2 = 0.

设A,B,C,D的列表长度为O(n), 则构造combine1和combine2的时间复杂度为O(n^{2}), combine1和combine2的长度也为O(n^{2}); 找出value1和value2,使得value1 + value2 = 0的时间复杂度也可以为O(n^{2}), 只要用combine2构造一个计数器combine2_counter, 键为combine2的元素,值为元素的计数,这样对于每一个combine1的元素value1,我们都可以以常数时间从combine2_counter取出value2 = -value1和它的计数。

所以总的时间复杂度为O(n^{2})

伪代码

4SumII(A, B, C, D)
target = 0
count = 0
combine1 = [x + y | x <- A, y <- B]
combine2 = [x + y | x <- C, y <- D]
construct combine2_counter such that keys of combine2_counter is elements of combine2, and values of combine2_counter is the number of each element in combine2
for value1 in combine1
    value2 = target - value1
    if value2 in combine2_counter
        count = count + combine2_counter[value2]
return count

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值