如何在数组中查找并返回重复值 [英] How to find and return a duplicate value in array

查看:27
本文介绍了如何在数组中查找并返回重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆