mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0001.两数之和.md Scala版本
This commit is contained in:
@ -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>
|
||||
|
Reference in New Issue
Block a user