[LeetCode] Find Common Elements Between Two Arrays

10031. Find Common Elements Between Two Arrays

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 that 0 <= i < n and nums1[i] occurs at least once in nums2.
  • The number of indices i such that 0 <= i < m and nums2[i] occurs at least once in nums1.

Return an integer array answer of size 2 containing the two values in the above order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
vector<int> findIntersectionValues(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> A(begin(nums1), end(nums1)), B(begin(nums2), end(nums2));
vector<int> res{0,0};
for(int i = 0; i < nums1.size(); i++) {
if(B.count(nums1[i])) res[0] += 1;
}
for(int i = 0; i < nums2.size(); i++) {
if(A.count(nums2[i])) res[1] += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/10/PS/LeetCode/find-common-elements-between-two-arrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.