添加 0349.两个数组的交集.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-13 10:05:27 +08:00
parent 74b76bfd12
commit 78c6602ff2

View File

@ -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