https://leetcode.com/problems/find-the-difference-of-two-arrays/description
Find the Difference of Two Arrays - LeetCode
Can you solve this real interview question? 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
leetcode.com
Q. 주어진 2개의 입력 배열 num1, num2에 대해 2개의 조건을 만족하는 vector를 출력하라.
이때 첫번째 vector에는 num1에는 있지만 num2에는 없는 원소들 모음을,
2번째 vector에는 num2에는 있지만 num1에는 없는 원소들 모음을 중복 없이 출력하라.
Solution.
hash를 쓰면 O(N)에 무난히 풀수 있는 문제.
vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2)
{
vector<vector<int>> vRet;
unordered_set<int> present, sRet;
for (int k = 0; k < nums2.size(); ++k)
{
if (present.find(nums2[k]) == present.end())
present.insert(nums2[k]);
}
for (int k = 0; k < nums1.size(); ++k)
{
if (present.find(nums1[k]) == present.end())
{
if (sRet.find(nums1[k]) == sRet.end())
sRet.insert(nums1[k]);
}
}
vRet.push_back(vector<int>(sRet.begin(), sRet.end()));
present.clear();
sRet.clear();
for (int k = 0; k < nums1.size(); ++k)
{
if (present.find(nums1[k]) == present.end())
present.insert(nums1[k]);
}
for (int k = 0; k < nums2.size(); ++k)
{
if (present.find(nums2[k]) == present.end())
{
if (sRet.find(nums2[k]) == sRet.end())
sRet.insert(nums2[k]);
}
}
vRet.push_back(vector<int>(sRet.begin(), sRet.end()));
return vRet;
}
'Leetcode > LeetCode75' 카테고리의 다른 글
[HashMap/Set][Medium] 1657. Determine if Two Strings Are Close (1) | 2023.12.10 |
---|---|
[HashMap/Set][Easy] 1207. Unique Number of Occurrences (0) | 2023.12.09 |
[PrefixSum][Easy] 724. Find Pivot Index (1) | 2023.12.08 |
[PrefixSum][Easy] 1732. Find the Highest Altitude (1) | 2023.12.07 |
[Sliding Window][Medium] 1493. Longest Subarray of 1's After Deleting One Element (1) | 2023.12.05 |