From abe00238f44718c49b9442c26e7f7b01f84be3e4 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Fri, 13 May 2022 16:37:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200001.=E4=B8=A4=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 9571a773..141e66f3 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -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) + } +} +``` -----------------------