scala - 在 Scala 中检查线性时间的数组内容相等性
问题描述
我想检查 2 个整数数组(目标和 arr)是否具有相同的内容(两个数组都是无序的)。示例:Array(1,1,3,4,1,5)
内容等于Array(1,1,1,5,4,3)
内容。我知道排序解决方案,我正在尝试制定线性时间解决方案。我首先获取目标数组的配置文件,target.groupBy(identity)
然后使用该配置文件折叠目标数组:
def canBeEqual(target: Array[Int], arr: Array[Int]): Boolean = {
import scala.collection.mutable.Map
var profile = target.groupBy(identity).view.mapValues(_.length).toMap
var mutableProfile = Map(profile.toSeq: _*)
arr.fold(mutableProfile)((p, x) => {p(x) = p(x) - 1; p}).isEmpty
}
我遇到的问题:
- 默认地图是不可变的,我使用可变地图重建了配置文件地图。这将如何影响性能?
- 我收到此编译错误:
Line 5: error: value update is not a member of Any (in solution.scala)
arr.fold(mutableProfile)((p, x) => {p(x) = p(x) - 1; p}).isEmpty
^
我添加了类型arr.fold(mutableProfile)((p:Map[Int,Int], x:Int) => {p(x) = p(x) - 1; p}).isEmpty
,但由于以下错误而失败:
Line 5: error: type mismatch; (in solution.scala)
found : (scala.collection.mutable.Map[Int,Int], Int) => scala.collection.mutable.Map[Int,Int]
required: (Any, Any) => Any
我目前被困在这一点上。无法弄清楚类型不匹配的问题。此外,任何有关如何以惯用方式(和有效)解决此问题的建议都值得赞赏。
- 免责声明 1:我是 Scala 初学者。上周开始阅读有关 Scala 的信息。
- 免责声明 2:以上问题是 leetcode 问题 #1460。
解决方案
不是通过算法修改,而是清除编译错误:
def canBeEqual(target: Array[Int], arr: Array[Int]): Boolean = {
if (target.length != arr.length) {
false
} else {
var profile = target.groupBy(identity).mapValues(_.length)
arr.forall(x =>
profile.get(x) match {
case Some(e) if e >= 1 =>
profile += (x -> (e - 1))
true
case Some(_) => false
case None => false
})
}
}
请注意,从不可变的 HashMap 中添加或删除需要恒定的时间。(参考:https ://docs.scala-lang.org/overviews/collections/performance-characteristics.html )
forall
首选,fold
因为当条件不匹配时,可以在两者之间中断。(尝试将打印语句放入匹配项以进行验证)
或者你可以这样做:
target.groupBy(identity).mapValues(_.length) == arr.groupBy(identity).mapValues(_.length)
推荐阅读
- android - 网站无法识别保存在 Smartlock 中的凭据
- amazon-ec2 - 如何创建可以休眠的 ec2 实例?
- python - __invert__ 方法
- c# - 标签属性上的 WPF MultiDataTrigger 仅触发一次
- c# - 使用自定义 dll 时 SISS 包损坏
- javascript - 逗号分隔、冒号或破折号分隔值的 MAC 地址正则表达式验证
- google-chrome - Joomla 页面有多少级缓存
- r - 重新采样/聚合 NetCDF 文件以解析第二个 NetCDF 文件
- android-studio - 此版本的 Android Studio 无法打开此项目,请使用 Android Studio 3.5 或更高版本重试
- python - 用不同列表中的元素(单词)替换列表中的元素(单词)