Skip to content

Commit 78c6602

Browse files
committed
添加 0349.两个数组的交集.md Scala版本
1 parent 74b76bf commit 78c6602

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

problems/0349.两个数组的交集.md

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,49 @@ int* intersection1(int* nums1, int nums1Size, int* nums2, int nums2Size, int* re
312312
return result;
313313
}
314314
```
315-
315+
Scala:
316+
317+
正常解法:
318+
```scala
319+
object Solution {
320+
def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = {
321+
// 导入mutable
322+
import scala.collection.mutable
323+
// 临时Set,用于记录数组1出现的每个元素
324+
val tmpSet: mutable.HashSet[Int] = new mutable.HashSet[Int]()
325+
// 结果Set,存储最终结果
326+
val resSet: mutable.HashSet[Int] = new mutable.HashSet[Int]()
327+
// 遍历nums1,把每个元素添加到tmpSet
328+
nums1.foreach(tmpSet.add(_))
329+
// 遍历nums2,如果在tmpSet存在就添加到resSet
330+
nums2.foreach(elem => {
331+
if (tmpSet.contains(elem)) {
332+
resSet.add(elem)
333+
}
334+
})
335+
// 将结果转换为Array返回,return可以省略
336+
resSet.toArray
337+
}
338+
}
339+
```
340+
骚操作1:
341+
```scala
342+
object Solution {
343+
def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = {
344+
// 先转为Set,然后取交集,最后转换为Array
345+
(nums1.toSet).intersect(nums2.toSet).toArray
346+
}
347+
}
348+
```
349+
骚操作2:
350+
```scala
351+
object Solution {
352+
def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = {
353+
// distinct去重,然后取交集
354+
(nums1.distinct).intersect(nums2.distinct)
355+
}
356+
}
357+
```
316358
## 相关题目
317359

318360
* 350.两个数组的交集 II

0 commit comments

Comments
 (0)