我想知道在哪些情况下使用哪些数据结构最适合进行“包含”或“存在”检查。
我提出这个问题是因为我来自Python背景,并习惯于对所有事情都使用if x in something:
表达式。例如,哪些表达式评估得最快:
val m = Map(1 -> 1, 2 -> 2, 3 -> 3, 4 -> 4)
//> m : scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3, 4
//| -> 4)
val l = List(1,2,3,4) //> l : List[Int] = List(1, 2, 3, 4)
val v = Vector(1,2,3,4) //> v : scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4)
m.exists(_._1 == 3) //> res0: Boolean = true
m.contains(3) //> res1: Boolean = true
l.exists(_ == 3) //> res2: Boolean = true
l.contains(3) //> res3: Boolean = true
v.exists(_ == 3) //> res4: Boolean = true
v.contains(3) //> res5: Boolean = true
直觉上,我认为对于随机检查,向量应该是最快的,而如果我们知道所检查的值在列表的开头并且有大量数据,则列表会更快。然而,欢迎确认或更正。此外,请随意扩展其他数据结构。
注意:如果您觉得这个问题过于模糊,请告诉我,因为我不确定我是否表达正确。
contains
应该是常数时间(不像exists
,它必须首先应用一些谓词,因此我认为它也是线性的)。 - om-nom-nom