求两链表元素对和为N的所有元素对

6 篇文章 0 订阅

有两个链表L1 ,L2.链表的链表的大小在十亿级。链表包含正数和负数。为了简便,假设他们都是整数。

给定整数N。现在找出L1+L2中的和为N的元素对。

L1 = 28, -7, 0, 56, 6, -8, 0, 72, 1000, -33
L2 = 53, 20, 27, -52, 99, 14, -8
N = 20
The answer will be:
(28, -8), (-7, 27), (0, 20), (6, 14), (0, 20), (72, -52)


You do have two linked list L1 and L2. The size of linked lists is huge and in billions. Linked List contains numbers (both negative and positive). For simplicity you can assume they are all integers.
You have been given a number say N. now you need to find out all of the pairs where one element from L1 + one element from L2 = N.
i.e.
L1 = 28, -7, 0, 56, 6, -8, 0, 72, 1000, -33
L2 = 53, 20, 27, -52, 99, 14, -8
N = 20
The answer will be:
(28, -8), (-7, 27), (0, 20), (6, 14), (0, 20), (72, -52)

假设不考虑重复,

list1 = 10, 10
list2 = 20
target N = 30,

只需要输出(10, 20)

如果list的大小很小,可以使用hash表来解决问题。关键是链表大小是十亿级的。有将近4十亿个整数,需要16GB的内存,如果我们将其全部存储在内存中--太大了。

我们可以使用bitmap:使用4十亿个bit去表示这些整数,话费512MB内存。如果整数在list1中出现,设置对应bit位为1.映射如下:使用前29bit计算偏移量,使用最后3bit计算应设置的bit位。000设置第0位为1,111设置第七位为1...(一个整数有32位)

使用这种密集的方式存储list1,对于list2的每一个元素去检查在list1中有没有对应的元素使得和为N。

以上就是线性时间的解法。

I am assuming that duplication does not matter: say
list1 = 10, 10
list2 = 20
target N = 30,
then we only need to output (10, 20). We do not need to output (10, 20), (10, 20)

If the list sizes are small, everyone knows the solution based on hash_set. The tricky part here is the list size (billions of integers). There are 4 billion integers, which requires 16GB memory if we store them in the memory ---- too large.

We can play the trick if bitmap encoding: we use 4 billion bits to represent the integers, which takes 512MB (much more reasonable now). If an integer appears in list1, we set the corresponding bit. The mapping is like this: calculate the byte offset using the first 29 bits, then calculate the bit to set using the last 3 bits (an integer has 32 bits in total).

After we store list1 using this compact way, we can check every element in list2 to see if there is an element in list1 to make the sum equal to N.

This is a linear time solution.





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值