Leetcode 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.Each integer in answer[0] and answer[1] must be unique and you may return the answer in any order.
nums1 and nums2.nums1 and add each distinct element to a set.nums2 and add each distinct element to a different set.nums1 not in nums2nums2 not in nums1#include <vector>
#include <unordered_set>
#include <algorithm>
std::vector<std::vector<int>> findDifference(std::vector<int>& nums1, std::vector<int>& nums2) {
// Create sets to store unique elements of both arrays
std::unordered_set<int> set1(nums1.begin(), nums1.end());
std::unordered_set<int> set2(nums2.begin(), nums2.end());
// Initialize the result vectors
std::vector<int> res1, res2;
// Find unique elements in nums1 not in nums2
for (int num : set1) {
if (set2.find(num) == set2.end()) {
res1.push_back(num);
}
}
// Find unique elements in nums2 not in nums1
for (int num : set2) {
if (set1.find(num) == set1.end()) {
res2.push_back(num);
}
}
return {res1, res2};
}
nums1 and m is the length of nums2.set1 and O(m) for set2.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?