【问题标题】:Efficient ay to process arrays处理数组的有效方法
【发布时间】:2013-06-04 22:21:55
【问题描述】:

假设我有以下数组。

数组 1:城市列表(可能有一些与数组 2 相同的条目) 数组2:城市列表

我想输出以下列表S:

  1. 仅在数组 1 中的城市列表
  2. 仅数组 2 中的城市列表
  3. 两个数组中的城市列表

完成1-3最有效的方法是什么?

我正在考虑将城市的名称存储在每个数组中,然后进行 foreach 来比较两者。

【问题讨论】:

  • 最好使用散列对象/字典来测试存在性。
  • 设置交集 是您想要做的事情的术语。您提出的建议可以完成这项工作,但这并不是最有效的方式。

标签: arrays sorting computer-science performance


【解决方案1】:

如果您的数组已排序,您可以并行遍历它们:

index_1 = 0 // assuming zero based indexing
index_2 = 0

repeat the follwoing loop:
if( index_0 is out of range )
  count (remaining) cities from array 2
else if( index_1 is out of range )
  count (remaining) cities from array 2
else {
a = get city from array 1 with the index_1
b = get city from array 2 with the index_2
if( a = b ) {
  increment no. of cities in both arrays
  increment both indices
}
else if( a < b )
  count cities from array 1 until city from array 2 is b, update indices
else 
  count cities from array 2 until city from array 1 is a, update indices
}
end loop

这应该在数组大小的线性时间内完成。

如果数组未排序,则使用有效的排序算法对其进行排序。

如果数组很小,请不要打扰,使用带有嵌套循环的蛮力方法。

【讨论】: