且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在数组中查找并返回重复值

更新时间:2022-11-13 22:29:30

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