【问题标题】:Remove duplicate values from array of arrays, keeping one copy of each unique value从数组数组中删除重复值,保留每个唯一值的一份副本
【发布时间】:2015-12-30 21:10:19
【问题描述】:

我有一个散列数组,每个散列包含一个超过 100,000 多个元素的大数组。

我编写了这个方法来删除每个内部数组中的重复项,只保留一个元素的副本,但遗憾的是,由于数组 - 运算符是好贵。

我试图减少的数据结构如下所示:

[{regex: "st.+", results: ["string1", "string2", "strong"]}, {regex: "string.+", results: ["string1", "string2"]}]

为了澄清,:regex 是一个用于从大型数组中查找字符串的正则表达式。这就是为什么相似的正则表达式会导致数组之间出现重复值的原因。

def uniqify(arr)
# This loops over an arry of arrays and compares each 
# array to the next, keeping only the unique values in each array
  i = 0
  while i < arr.length
    a = arr[i][:results]
    j = i + 1
    while j < arr.length
      b = arr[j][:results]
      arr[j][:results] = b - a
      j += 1
    end
    i += 1
  end
  arr
end

我的示例数据的预期输出应该是:

[{regex: "st.+", results: ["string1", "string2", "strong"]}, {regex: "string.+", results: []}]

我怎样才能使这个循环功能更好?

【问题讨论】:

  • 只是为了澄清一下,对于我的用途,哪个数组具有唯一值并不重要,重要的是每个值在整个数组数组中表示一次。
  • 还需要保留数组组,还是可以用一维数组来表示唯一值?
  • 我仍然必须保持组中的唯一值。这是因为不与任何其他数组共享的唯一值与我必须关联此数据的哈希相关。
  • 在处理这么多数据时,某种数据库不是更合适吗?
  • 为了帮助潜在的回答者,您需要显示您预期的输出数组是什么。您还需要编写一些基准测试来测试实现代码的各种方式。认为您可以编写比内置 - 更快的东西可能不是一个好的假设,基准会显示。

标签: arrays ruby multidimensional-array unique


【解决方案1】:

我认为你的问题的一部分是你正在做 O(n^2) 数组减法(对于每个数组,你检查它前面的所有其他数组,这是很多浪费的努力)。一项改进可能是保留一组包含您在此过程中看到的所有内容。这只需要处理每个数组一次,加上集合可以廉价地检查它们是否包含一个元素。

require 'set'

def uniquify!(arrays)
  seen = Set.new
  arrays.each do |array|
    i = 0
    while i < array.length
      current = array[i]
      if seen.include? current
        array.delete_at(i)
      else
        seen.add(current)
        i += 1
      end
    end
  end
end

这会就地修改参数数组(因此我在名称中添加了结尾的 !)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 2020-09-20
    • 2011-12-13
    相关资源
    最近更新 更多