【问题标题】:get all indexes of value nil in array获取数组中所有值为 nil 的索引
【发布时间】:2018-02-25 06:31:20
【问题描述】:

我有一个N 元素数组,这个数组包含01nil。 我想获取存在nil 的所有索引或对数组进行排序,以便所有nil 排在第一位。

我正在寻找一种有效的方法,因为数组大小可能非常大。

这是我的代码

array_of data # array with lots of 1, 0 and nil
temp = []
array_of_data.each_with_index {|a,i| (array_of_data[i] ? true : temp << i )}

【问题讨论】:

  • CPU 高效还是内存高效?
  • 如果可能的话,更重要的是 CPU 效率。
  • 是否需要保留原始数组?
  • 其实我会尝试两种方式保留原始数组而不是保留它。

标签: arrays ruby performance sorting memory-efficient


【解决方案1】:

供您进行基准测试的替代方案:

# Indices of non-nil values
res = ary.map.with_index{ |v,i| i if v }.compact
res = [].tap{ |r| ary.each.with_index{ |v,i| r<<i if v } }
ary.map!.with_index{ |v,i| v && i }.compact

# Sorting the array so that nil comes first (possibly re-ordering the others)
res = ary.sort_by{ |v| v ? 1 : -1 }
ary.sort_by!{ |v| v ? 1 : -1 }

# Sorting the array so that nil comes first, order of others unchanged
res = ary.sort_by.with_index{ |v,i| v ? i : -1 }
ary.sort_by!.with_index{ |v,i| v ? i : -1 }

【讨论】:

  • each.with_index 或 each_with_index?
猜你喜欢
  • 1970-01-01
  • 2018-12-09
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
相关资源
最近更新 更多