我有一个值“狗”和一个数组[“猫”、“狗”、“鸟”]。

如何在不循环的情况下检查数组中是否存在它?是否有一种简单的方法来检查该值是否存在?


当前回答

在任何数组中查找元素有多种方法,但最简单的方法是“in?”方法

example:
arr = [1,2,3,4]
number = 1
puts "yes #{number} is present in arr" if number.in? arr

其他回答

这边怎么样?

['Cat', 'Dog', 'Bird'].index('Dog')

值得一提的是,Ruby文档是解决此类问题的绝佳资源。

我还要注意您正在搜索的数组的长度。包括?方法将运行一个复杂度为O(n)的线性搜索,这可能会变得非常难看,这取决于数组的大小。

如果您使用的是一个大的(排序的)数组,我会考虑编写一个二进制搜索算法,它应该不会太难,而且最坏的情况是O(logn)。

或者如果您使用的是Ruby 2.0,您可以利用bsarch。

如果需要多次检查任何键,请将arr转换为哈希,然后检查O(1)

arr = ['Cat', 'Dog', 'Bird']
hash = arr.map {|x| [x,true]}.to_h
 => {"Cat"=>true, "Dog"=>true, "Bird"=>true}
hash["Dog"]
 => true
hash["Insect"]
 => false

Hash#has_key的性能?与Array#include相比?

Parameter              Hash#has_key?                 Array#include 

Time Complexity         O(1) operation                O(n) operation 

Access Type             Accesses Hash[key] if it      Iterates through each element
                        returns any value then        of the array till it
                        true is returned to the       finds the value in Array
                        Hash#has_key? call
                        call    

对于一次性检查,使用include?很好

有多种方法可以实现这一点。其中一些如下:

a = [1,2,3,4,5]

2.in? a  #=> true

8.in? a #=> false

a.member? 1 #=> true

a.member? 8 #=> false

您正在查找包含项?:

>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true