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

来源:互联网 发布:mac词典 编辑:程序博客网 时间:2024/05/18 01:08

有两个链表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.





原创粉丝点击