添加 0454.四数相加II.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-13 17:28:14 +08:00
parent abe00238f4
commit 53379c023f

View File

@ -318,5 +318,41 @@ impl Solution {
}
```
Scala:
```scala
object Solution {
// 导包
import scala.collection.mutable
def fourSumCount(nums1: Array[Int], nums2: Array[Int], nums3: Array[Int], nums4: Array[Int]): Int = {
// 定义一个HashMapkey存储值value存储该值出现的次数
val map = new mutable.HashMap[Int, Int]()
// 遍历前两个数组把他们所有可能的情况都记录到map
for (i <- nums1.indices) {
for (j <- nums2.indices) {
val tmp = nums1(i) + nums2(j)
// 如果包含该值则对他的key加1不包含则添加进去
if (map.contains(tmp)) {
map.put(tmp, map.get(tmp).get + 1)
} else {
map.put(tmp, 1)
}
}
}
var res = 0 // 结果变量
// 遍历后两个数组
for (i <- nums3.indices) {
for (j <- nums4.indices) {
val tmp = -(nums3(i) + nums4(j))
// 如果map中存在该值结果就+=value
if (map.contains(tmp)) {
res += map.get(tmp).get
}
}
}
// 返回最终结果可以省略关键字return
res
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>