题目
给你两个下标从 0 开始的整数数组 nums1 和 nums2 ,它们分别含有 n 和 m 个元素。
请你计算以下两个数值:
- 统计
0 <= i < n中的下标i,满足nums1[i]在nums2中 至少 出现了一次。 - 统计
0 <= i < m中的下标i,满足nums2[i]在nums1中 至少 出现了一次。
请你返回一个长度为 2 的整数数组 **answer ,按顺序 分别为以上两个数值。
思路
通过两个 set 来判断是否有存在的数字
代码
class Solution {
public int[] findIntersectionValues(int[] nums1, int[] nums2) {
int count = 0;
int[] ans = new int[2];
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int i : nums1) {
set1.add(i);
}
for (int i : nums2) {
set2.add(i);
if (set1.contains(i)) count++;
}
ans[1] = count;
count = 0;
for (int i : nums1) {
if (set2.contains(i)) count++;
}
ans[0] = count;
return ans;
}
}