//参考《快学scala》 集合操作 foldLeft page:180
package alogrithnm
import scala.collection.mutable.Map
object CombineTwoMap {
def main(args: Array[String]): Unit = {
val map1 = Map[String, Int]("a" -> 1, "b" -> 1, "c" -> 1)
//val map1 = Map[String, Int]("a" -> 1, "b" -> 1, "c" -> 1,"d"->1,"f"->1,"g"->1)
val map2 = Map("a" -> 1, "z" -> 1, "c" -> 1, "d" -> 1)
val result = combinerTwoMap(map1, map2)
for ((k, v) <- result) {
println(k + " " + v)
}
}
def combinerTwoMap(a: Map[String, Int], b: Map[String, Int]): Map[String, Int] = {
(a /: b) {
case (map, (k, v)) =>
println(k + " " + v)
map + (k -> (v + map.getOrElse(k, 0)))
case _ =>
println("not match")
null
}
}
}
时间复杂度O(N)取决于size较小的那个map长度。