mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
添加 0454.四数相加II.md Scala版本
This commit is contained in:
@ -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>
|
||||
|
Reference in New Issue
Block a user