[LeetCode] Find the Difference of Two Arrays

2215. Find the Difference of Two Arrays

Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:

  • answer[0] is a list of all distinct integers in nums1 which are not present in nums2.
  • answer[1] is a list of all distinct integers in nums2 which are not present in nums1.

Note that the integers in the lists may be returned in any order.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> us1(begin(nums1), end(nums1));
unordered_set<int> us2(begin(nums2), end(nums2));
vector<int> res1, res2;
for(auto n : nums1) if(!us2.count(n)) res1.push_back(n), us2.insert(n);
for(auto n : nums2) if(!us1.count(n)) res2.push_back(n), us1.insert(n);
return {res1,res2};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/03/PS/LeetCode/find-the-difference-of-two-arrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.