From 78c6602ff20c309132007795956f332d66ff7130 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Fri, 13 May 2022 10:05:27 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200349.=E4=B8=A4=E4=B8=AA?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E7=9A=84=E4=BA=A4=E9=9B=86.md=20Scala?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0349.两个数组的交集.md | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 45f19b6e..49cf4112 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -312,7 +312,49 @@ int* intersection1(int* nums1, int nums1Size, int* nums2, int nums2Size, int* re return result; } ``` +Scala: +正常解法: +```scala +object Solution { + def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = { + // 导入mutable + import scala.collection.mutable + // 临时Set,用于记录数组1出现的每个元素 + val tmpSet: mutable.HashSet[Int] = new mutable.HashSet[Int]() + // 结果Set,存储最终结果 + val resSet: mutable.HashSet[Int] = new mutable.HashSet[Int]() + // 遍历nums1,把每个元素添加到tmpSet + nums1.foreach(tmpSet.add(_)) + // 遍历nums2,如果在tmpSet存在就添加到resSet + nums2.foreach(elem => { + if (tmpSet.contains(elem)) { + resSet.add(elem) + } + }) + // 将结果转换为Array返回,return可以省略 + resSet.toArray + } +} +``` +骚操作1: +```scala +object Solution { + def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = { + // 先转为Set,然后取交集,最后转换为Array + (nums1.toSet).intersect(nums2.toSet).toArray + } +} +``` +骚操作2: +```scala +object Solution { + def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = { + // distinct去重,然后取交集 + (nums1.distinct).intersect(nums2.distinct) + } +} +``` ## 相关题目 * 350.两个数组的交集 II