如何在数组中查找并返回重复值 [英] How to find and return a duplicate value in array
问题描述
arr
是字符串数组:
["hello", "world", "stack", "overflow", "hello", "again"]
一种简单又优雅的方法来检查arr
是否存在重复项,如果重复,则返回其中一个重复项(无论哪个)?
What would be an easy and elegant way to check if arr
has duplicates, and if so, return one of them (no matter which)?
示例:
["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 }
我知道这不是一个很好的答案,但是我喜欢它.这是一个漂亮的班轮代码.除非您需要处理海量数据集,否则它工作得很好.
I know this isn't very elegant answer, but I love it. It's beautiful one liner code. And works perfectly fine unless you need to process huge data set.
正在寻找更快的解决方案?来啦!
Looking for faster solution? Here you go!
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),但现在需要管理多行代码,需要测试用例等.
It's linear, O(n), but now needs to manage multiple lines-of-code, needs test cases, etc.
如果您需要更快的解决方案,请尝试使用C.
If you need an even faster solution, maybe try C instead.
以下是比较不同解决方案的要点: https://gist.github.com/naveed -ahmad/8f0b926ffccf5fbd206a1cc58ce9743e
And here is the gist comparing different solutions: https://gist.github.com/naveed-ahmad/8f0b926ffccf5fbd206a1cc58ce9743e
这篇关于如何在数组中查找并返回重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!