Skip to content

Commit

Permalink
添加 0454.四数相加II.md Scala版本
Browse files Browse the repository at this point in the history
  • Loading branch information
wzqwtt committed May 13, 2022
1 parent abe0023 commit 53379c0
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions problems/0454.四数相加II.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
// 定义一个HashMap,key存储值,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>

0 comments on commit 53379c0

Please sign in to comment.