找到两个数组中的公共元素
难度:
标签:
题目描述
You are given two 0-indexed integer arrays nums1
and nums2
of sizes n
and m
, respectively.
Consider calculating the following values:
- The number of indices
i
such that0 <= i < n
andnums1[i]
occurs at least once innums2
. - The number of indices
i
such that0 <= i < m
andnums2[i]
occurs at least once innums1
.
Return an integer array answer
of size 2
containing the two values in the above order.
Example 1:
Input: nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6] Output: [3,4] Explanation: We calculate the values as follows: - The elements at indices 1, 2, and 3 in nums1 occur at least once in nums2. So the first value is 3. - The elements at indices 0, 1, 3, and 4 in nums2 occur at least once in nums1. So the second value is 4.
Example 2:
Input: nums1 = [3,4,2,3], nums2 = [1,5] Output: [0,0] Explanation: There are no common elements between the two arrays, so the two values will be 0.
Constraints:
n == nums1.length
m == nums2.length
1 <= n, m <= 100
1 <= nums1[i], nums2[i] <= 100
代码结果
运行时间: 32 ms, 内存: 16.6 MB
/*
* 思路:
* 1. 使用 Java Stream API,将 nums2 转换为集合,以快速查找 nums1 中的元素。
* 2. 使用 Stream 过滤 nums1 中存在于 nums2 集合中的元素并计数。
* 3. 同样的方法对 nums2 进行操作,计算存在于 nums1 集合中的元素个数。
* 4. 返回结果数组,其中第一个元素为 nums1 中的计数,第二个元素为 nums2 中的计数。
*/
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class Solution {
public int[] countMatches(int[] nums1, int[] nums2) {
Set<Integer> setNums2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
long count1 = Arrays.stream(nums1).filter(setNums2::contains).count();
Set<Integer> setNums1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
long count2 = Arrays.stream(nums2).filter(setNums1::contains).count();
return new int[]{(int) count1, (int) count2};
}
}
解释
方法:
此题解使用了集合来找出两个数组中的公共元素。首先,将nums1和nums2转换为集合set1和set2,这样可以去除重复元素,并且利用集合的高效查找特性。然后,分别计算nums1中有多少个元素存在于set2中,以及nums2中有多少个元素存在于set1中。这两个计数结果构成了最终的返回值。
时间复杂度:
O(n + m)
空间复杂度:
O(n + m)
代码细节讲解
🦆
在这个解法中,为什么选择使用集合而不是其他数据结构来处理元素查找?
▷🦆
在计算nums1中的元素是否存在于set2中时,代码使用了生成器表达式而非列表推导,这样做有什么优点?
▷🦆
代码中使用`sum(1 for num in nums1 if num in set2)`来计算匹配的元素数量,是否有更直观或效率更高的实现方式?
▷🦆
本题解中有考虑到元素的顺序对结果的影响吗,如果数组中的元素顺序变化,输出结果会受到影响吗?
▷