|
1 | 1 | [#0350-intersection-of-two-arrays-ii]
|
2 |
| -= 350. Intersection of Two Arrays II |
| 2 | += 350. 两个数组的交集 II |
3 | 3 |
|
4 |
| -{leetcode}/problems/intersection-of-two-arrays-ii/[LeetCode - Intersection of Two Arrays II^] |
| 4 | +https://leetcode.cn/problems/intersection-of-two-arrays-ii/[LeetCode - 350. 两个数组的交集 II ^] |
5 | 5 |
|
6 |
| -Given two arrays, write a function to compute their intersection. |
| 6 | +给你两个整数数组 `nums1` 和 `nums2`,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。 |
7 | 7 |
|
8 |
| -*Example 1:* |
9 |
| - |
10 |
| -[subs="verbatim,quotes,macros"] |
11 |
| ----- |
12 |
| -*Input:* nums1 = [1,2,2,1], nums2 = [2,2] |
13 |
| -*Output:* [2,2] |
14 |
| ----- |
15 |
| - |
16 |
| - |
17 |
| -*Example 2:* |
18 |
| - |
19 |
| -[subs="verbatim,quotes,macros"] |
20 |
| ----- |
21 |
| -*Input:* nums1 = [4,9,5], nums2 = [9,4,9,8,4] |
22 |
| -*Output:* [4,9] |
23 |
| ----- |
| 8 | +*示例 1:* |
24 | 9 |
|
| 10 | +.... |
| 11 | +输入:nums1 = [1,2,2,1], nums2 = [2,2] |
| 12 | +输出:[2,2] |
| 13 | +.... |
25 | 14 |
|
26 |
| -*Note:* |
| 15 | +*示例 2:* |
27 | 16 |
|
| 17 | +.... |
| 18 | +输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4] |
| 19 | +输出:[4,9] |
| 20 | +.... |
28 | 21 |
|
29 |
| -* Each element in the result should appear as many times as it shows in both arrays. |
30 |
| -* The result can be in any order. |
31 | 22 |
|
| 23 | +*提示:* |
32 | 24 |
|
33 |
| -*Follow up:* |
| 25 | +* `+1 <= nums1.length, nums2.length <= 1000+` |
| 26 | +* `+0 <= nums1[i], nums2[i] <= 1000+` |
34 | 27 |
|
| 28 | +**进阶*:* |
35 | 29 |
|
36 |
| -* What if the given array is already sorted? How would you optimize your algorithm? |
37 |
| -* What if _nums1_'s size is small compared to _nums2_'s size? Which algorithm is better? |
38 |
| -* What if elements of _nums2_ are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? |
| 30 | +* 如果给定的数组已经排好序呢?你将如何优化你的算法? |
| 31 | +* 如果 `nums1` 的大小比 `nums2` 小,哪种方法更优? |
| 32 | +* 如果 `nums2` 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办? |
39 | 33 |
|
40 | 34 |
|
| 35 | +== 思路分析 |
41 | 36 |
|
| 37 | +最初思路是分别对两个数组遍历,使用 `Map` 来统计每个数字出现的次数,然后求交集。其实,只需要对一个数组统计每个数字出现的次数即可,在另外一个数组遍历时,根据次数来判断是否重复。可以介绍一个“取交集”的遍历。 |
42 | 38 |
|
43 | 39 | [[src-0350]]
|
| 40 | +[tabs] |
| 41 | +==== |
| 42 | +一刷:: |
| 43 | ++ |
| 44 | +-- |
44 | 45 | [{java_src_attr}]
|
45 | 46 | ----
|
46 | 47 | include::{sourcedir}/_0350_IntersectionOfTwoArraysIi.java[tag=answer]
|
47 | 48 | ----
|
| 49 | +-- |
| 50 | +
|
| 51 | +二刷:: |
| 52 | ++ |
| 53 | +-- |
| 54 | +[{java_src_attr}] |
| 55 | +---- |
| 56 | +include::{sourcedir}/_0350_IntersectionOfTwoArraysIi_2.java[tag=answer] |
| 57 | +---- |
| 58 | +-- |
| 59 | +==== |
| 60 | +
|
| 61 | +
|
| 62 | +== 参考资料 |
| 63 | +
|
48 | 64 |
|
0 commit comments