mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0349.两个数组的交集.md Scala版本
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user