Algorithm/문제풀이

[Leetcode] 350. Intersection of Two Arrays II 문제 풀이

bluespacedev 2021. 9. 17. 21:13

https://leetcode.com/problems/intersection-of-two-arrays-ii/

 

Intersection of Two Arrays II - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제 내용

숫자 집합 2개가 주어지는 데 교집합을 구하면 된다.

Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

 

문제 풀이

숫자 범위가 크지 않기 때문에 hash를 사용해서 풀었다.

1번째 배열의 숫자 빈도수를 구한다음에

2번째 배열에 숫자가 있는 지 찾고 있으면 교집합으로 정의했다.

 

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int, int> hash;
        for (auto num : nums1) {
            if (hash.find(num) == hash.end()) {
                hash[num] = 1;
            } else {
                hash[num]++;
            }
        }
        
        vector<int> ans;
        for (auto num : nums2) {
            if (hash.find(num) == hash.end() || hash[num] == 0)
                continue;
            
            hash[num]--;
            ans.push_back(num);
        }
        return ans;
    }
};