arr
是字符串数组:
["hello", "world", "stack", "overflow", "hello", "again"]
检查 arr
是否有重复项的简单而优雅的方法是什么,如果有,则返回其中一个(无论是哪个)?
例子:
["A", "B", "C", "B", "A"] # => "A" or "B"
["A", "B", "C"] # => nil
最佳答案
a = ["A", "B", "C", "B", "A"]
a.detect{ |e| a.count(e) > 1 }
我知道这不是一个非常优雅的答案,但我喜欢它。这是一个漂亮的类轮代码。除非你需要处理庞大的数据集,否则工作得很好。
正在寻找更快的解决方案?给你!
def find_one_using_hash_map(array)
map = {}
dup = nil
array.each do |v|
map[v] = (map[v] || 0 ) + 1
if map[v] > 1
dup = v
break
end
end
return dup
end
它是线性的,O(n),但现在需要管理多行代码,需要测试用例等。
如果您需要更快的解决方案,不妨试试 C。
这里是比较不同解决方案的要点:https://gist.github.com/naveed-ahmad/8f0b926ffccf5fbd206a1cc58ce9743e
关于ruby - 如何查找并返回数组中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8921999/