更新时间:2022-11-13 22:29:18
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