Input: nums1 =[4,3,2,3,1], nums2 =[2,2,5,2,3,6]Output: [3,4]Explanation:
The elements at indices 1,2, and 3in`nums1` exist in`nums2` as well. So
`answer1`is3.The elements at indices 0,1,3, and 4in`nums2` exist in`nums1`. So
`answer2`is4.
classSolution {
publicint[]findIntersectionValues(int[] nums1, int[] nums2) {
Set<Integer> s2 =new HashSet<>();
for (int n : nums2) s2.add(n);
int ans1 = 0;
for (int n : nums1) if (s2.contains(n)) ans1++;
Set<Integer> s1 =new HashSet<>();
for (int n : nums1) s1.add(n);
int ans2 = 0;
for (int n : nums2) if (s1.contains(n)) ans2++;
returnnewint[]{ans1, ans2};
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funfindIntersectionValues(nums1: IntArray, nums2: IntArray): IntArray {
val s2 = nums2.toSet()
val ans1 = nums1.count { itin s2 }
val s1 = nums1.toSet()
val ans2 = nums2.count { itin s1 }
return intArrayOf(ans1, ans2)
}
}
1
2
3
4
5
6
7
classSolution:
deffindIntersectionValues(self, nums1: list[int], nums2: list[int]) -> list[int]:
s2 = set(nums2)
ans1 = sum(n in s2 for n in nums1)
s1 = set(nums1)
ans2 = sum(n in s1 for n in nums2)
return [ans1, ans2]
1
2
3
4
5
6
7
8
9
10
impl Solution {
pubfnfind_intersection_values(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
use std::collections::HashSet;
let s2: HashSet<_>= nums2.iter().collect();
let ans1 = nums1.iter().filter(|n| s2.contains(n)).count() asi32;
let s1: HashSet<_>= nums1.iter().collect();
let ans2 = nums2.iter().filter(|n| s1.contains(n)).count() asi32;
vec![ans1, ans2]
}
}