目标
给你两个下标从 0 开始的整数数组 nums1 和 nums2 ,它们分别含有 n 和 m 个元素。
请你计算以下两个数值:
- 统计 0 <= i < n 中的下标 i ,满足 nums1[i] 在 nums2 中 至少 出现了一次。
- 统计 0 <= i < m 中的下标 i ,满足 nums2[i] 在 nums1 中 至少 出现了一次。
请你返回一个长度为 2 的整数数组 answer ,按顺序 分别为以上两个数值。
示例 1:
输入:nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6]
输出:[3,4]
解释:分别计算两个数值:
- nums1 中下标为 1 ,2 和 3 的元素在 nums2 中至少出现了一次,所以第一个值为 3 。
- nums2 中下标为 0 ,1 ,3 和 4 的元素在 nums1 中至少出现了一次,所以第二个值为 4 。
示例 2:
输入:nums1 = [3,4,2,3], nums2 = [1,5]
输出:[0,0]
解释:两个数组中没有公共元素,所以两个值都为 0 。
说明:
- n == nums1.length
- m == nums2.length
- 1 <= n, m <= 100
- 1 <= nums1[i], nums2[i] <= 100
思路
有两个数组,统计在当前数组中出现,同时也在另一数组中出现的元素个数,即公共元素个数。数组 [1, 1, 1, 2]
与 [1, 2, 3]
的公共元素是 1,2
,公共元素个数分别是 4、2
。
常规的做法是使用HashSet分别保存数组元素,然后再次遍历数组判断是否是公共元素。由于数据范围比较小,可以直接使用数组计数。
代码
/**
* @date 2024-07-16 0:14
*/
public class FindIntersectionValues2956 {
/**
* 改进
*/
public int[] findIntersectionValues_v1(int[] nums1, int[] nums2) {
int[] count1 = new int[101];
for (int i : nums1) {
count1[i]++;
}
int a = 0, b = 0;
for (int i : nums2) {
if (count1[i] != 0) {
b++;
a += count1[i] == -1 ? 0 : count1[i];
count1[i] = -1;
}
}
return new int[]{a, b};
}
public int[] findIntersectionValues(int[] nums1, int[] nums2) {
int[] count1 = new int[101];
int[] count2 = new int[101];
for (int i : nums1) {
count1[i]++;
}
for (int i : nums2) {
count2[i]++;
}
int a = 0;
int b = 0;
for (int i = 0; i < 101; i++) {
if (count1[i] > 0) {
b += count2[i];
}
if (count2[i] > 0) {
a += count1[i];
}
}
return new int[]{a, b};
}
}