添加 0001.两数之和.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-13 16:37:39 +08:00
parent 05384d58d8
commit abe00238f4

View File

@ -274,6 +274,27 @@ class Solution {
}
}
```
Scala:
```scala
object Solution {
// 导入包
import scala.collection.mutable
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
// key存储值value存储下标
val map = new mutable.HashMap[Int, Int]()
for (i <- nums.indices) {
val tmp = target - nums(i) // 计算差值
// 如果这个差值存在于map则说明找到了结果
if (map.contains(tmp)) {
return Array(map.get(tmp).get, i)
}
// 如果不包含把当前值与其下标放到map
map.put(nums(i), i)
}
// 如果没有找到直接返回一个空的数组return关键字可以省略
new Array[Int](2)
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>