如何确定在数据的两个列表的差异 [英] How to determine differences in two lists of data

查看:135
本文介绍了如何确定在数据的两个列表的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个练习CS家伙闪耀着理论。

This is an exercise for the CS guys to shine with the theory.

假设你有2个集装箱的元素。文件夹,网址,文件,字符串,它其实并不重要。

Imagine you have 2 containers with elements. Folders, URLs, Files, Strings, it really doesn't matter.

什么是算法计算添加和删除?

What is AN algorithm to calculate the added and the removed?

的通知:如果有许多办法来解决这个问题,请后每回答一个,这样就可以分析并表决了

Notice: If there are many ways to solve this problem, please post one per answer so it can be analysed and voted up.

修改:所有的答案解决了与4容器此事。是否有可能只使用最初的2?

Edit: All the answers solve the matter with 4 containers. Is it possible to use only the initial 2?

推荐答案

假设你有一个独特的项目两个列表,以及顺序没有关系,你可以把他们两个作为集,而不是列出

Assuming you have two lists of unique items, and the ordering doesn't matter, you can think of them both as sets rather than lists

如果您认为维恩图,用列表A作为一个圆圈和名单B为其他,那么这两者的交集是常量池中。

If you think of a venn diagram, with list A as one circle and list B as the other, then the intersection of these two is the constant pool.

删除从A和B在此交汇的所有元素,和任何留在已被删除,而任何东西留在B已经被添加。

Remove all the elements in this intersection from both A and B, and and anything left in A has been deleted, whilst anything left in B has been added.

所以,遍历寻找B.每个项目。如果你找到它,从A和B都将其删除

So, iterate through A looking for each item in B. If you find it, remove it from both A and B

则A是事情已删除的列表,而B是添加的事情的清单

Then A is a list of things that were deleted, and B is a list of things that were added

我想...

好吧,随着新只有2容器的限制,同样仍持有:

[edit] Ok, with the new "only 2 container" restriction, the same still holds:

foreach( A ) { 
  if( eleA NOT IN B ) {
    DELETED
  }
}
foreach( B ) {
  if( eleB NOT IN A ) {
    ADDED
  }
}

那么你就不是构建一个新的列表,或破坏你的旧...但它会需要更长的时间,与在previous例如,你可以只遍历所有的短名单,并从较长删除元素。在这里,你需要做的两份名单

Then you aren't constructing a new list, or destroying your old ones...but it will take longer as with the previous example, you could just loop over the shorter list and remove the elements from the longer. Here you need to do both lists

这是我要说我的第一个解决方案没有使用4容器,它只是毁坏了二; - )

An I'd argue my first solution didn't use 4 containers, it just destroyed two ;-)

这篇关于如何确定在数据的两个列表的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆