比较两个 NSArray 并返回差异数
如何获取两个 NSArray,比较它们,然后返回差异的数量,最好是不同对象的数量,例如:
数组 1: 一 二 三个
数组2: 二 四 我
希望返回“1”
How can I take two NSArrays, compare them, then return the number of differences, preferably the number of different objects, for example:
Array 1:
one
two
three
Array 2:
two
four
one
I would like that to return "1"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用中间 NSMutableArray:
这样,只会删除公共元素。
You can do this by using an intermediate NSMutableArray:
With that way, only common elements will be removed.
我发现上面的答案没有考虑不同大小的数组。如果你按照上面的方法做,你应该检查哪个 array.count 更小,
或者
我将它们都设置为 NSSet,然后进行比较。
这样尺寸和顺序都得到正确处理! (我不需要知道差异的数量)
I found that the answer above didn't take arrays of differing size into account. If you do it as above, you should check to see which array.count is smaller and
OR
I made them both NSSets and then compared.
That way size and order are both dealt with properly! (I didn't need to know the number of differences)